#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