Free mag vol1 | Page 219

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II } Now, what if you create a method that allows the caller to send in the Person object by value (note the lack of parameter modifiers, such as out or ref): static void SendAPersonByValue(Person p) { // Change the age of "p"? p.personAge = 99; // Will the caller see this reassignment? p = new Person("Nikki", 99); } Notice how the SendAPersonByValue() method attempts to reassign the incoming Person reference to a new Person object, as well as change some state data. Now let’s test this method using the following Main() method: static void Main(string[] args) { // Passing ref-types by value. Console.WriteLine("***** Passing Person object by value *****"); Person fred = new Person("Fred", 12); Console.WriteLine("\nBefore by value call, Person is:"); fred.Display(); SendAPersonByValue(fred); Console.WriteLine("\nAfter by value call, Person is:"); fred.Display(); Console.ReadLine(); } The following is the output of this call: ***** Passing Person object by value ***** Before by value call, Person is: Name: Fred, Age: 12 After by value call, Person is: Name: Fred, Age: 99 As you can see, the value of personAge has been modified. This behavior seems to fly in the face of what it means to pass a parameter “by value.” Given that you were able to change the state of the incoming Person, what was copied? The answer: a copy of the reference to the caller’s object. Therefore, as the SendAPersonByValue() method is pointing to the same object as the caller, it is possible to alter the object’s state data. What is not possible is to reassign what the reference is pointing to. 154