#265 – Passing Reference Types by Value

Recall that by default parameters are passed by value to a method.  A copy of the variable is passed to the method, which means that if the method changes the parameter’s value, the change won’t be seen by the calling code.

If a parameter’s type is a reference type, however, what is passed by value to the method is a reference to the object.  This means that while the method can’t change the reference, it can change aspects of the object that is referenced.

As an example, assume that we have a Dog.BarkAt method that takes a reference to another Dog.  In the code below, the BarkAt method actually changes the target dog’s BarkPhrase.

        public void BarkAt(Dog target)
        {
            Console.WriteLine("I say {0} to {1}", BarkPhrase, target.Name);

            // I can change target dog's properties
            target.BarkPhrase = "I-am-a-dope";
        }

This change is seen by the calling code.

Advertisements