Free mag vol1 | Page 220

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II Passing Reference Types by Reference Now assume you have a SendAPersonByReference() method, which passes a reference type by reference (note the ref parameter modifier): static void SendAPersonByReference(ref Person p) { // Change some data of "p". p.personAge = 555; } // "p" is now pointing to a new object on the heap! p = new Person("Nikki", 999); As you might expect, this allows complete flexibility of how the callee is able to manipulate the incoming parameter. Not only can the callee change the state of the object, but if it so chooses, it may also reassign the reference to a new Person object. Now ponder the following updated Main() method: static void Main(string[] args) { // Passing ref-types by ref. Console.WriteLine("***** Passing Person object by reference *****"); ... Person mel = new Person("Mel", 23); Console.WriteLine("Before by ref call, Person is:"); mel.Display(); } SendAPersonByReference(ref mel); Console.WriteLine("After by ref call, Person is:"); mel.Display(); Console.ReadLine(); Notice the following output: ***** Passing Person object by reference ***** Before by ref call, Person is: Name: Mel, Age: 23 After by ref call, Person is: Name: Nikki, Age: 999 As you can see, an object named Mel returns after the call as an object named Nikki, as the method was able to change what the incoming reference pointed to in memory. The golden rule to keep in mind when passing reference types is the following: • If a reference type is passed by reference, the callee may change the values of the object’s state data, as well as the object it is referencing. • If a reference type is passed by value, the callee may change the values of the object’s state data, but not the object it is referencing. 155