#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #265 – Passing Reference Types by Value

  1. Pingback: #266 – You Can’t Prevent a Method from Changing the Contents of Reference Types « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: