#264 – By Default, Parameters Are Passed by Value

By default, parameters are passed to a method by value, which means that a copy of each parameter is made and passed to the method.

Because the method works with a copy of the data, changes made to a parameter are not visible outside the method.  Parameters passed by value can be thought of as input parameters.

For example, assume that we have the following Bark method, which takes a parameter named barkPhrase.  Notice that we attempt to change the value of barkPhrase before returning to the caller.

        public void Bark(string barkPhrase)
        {
            Console.WriteLine("{0} says: {1}", Name, barkPhrase);

            barkPhrase = "Yowza!";     // Just changing our copy
        }

Assume that we called the Bark method as follows:

            string myBark = "Wooferooni";
            kirby.Bark(myBark);

We can verify in the debugger that the myBark variable does not change when we call the Bark method.

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.

2 Responses to #264 – By Default, Parameters Are Passed by Value

  1. Pingback: #265 – Passing Reference Types by Value « 2,000 Things You Should Know About C#

  2. Pingback: #674 – Can Overload If Parameters Differ Only by ref Modifier « 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: