#271 – Passing a Reference Type as an Output Parameter

You can pass a reference-typed variable to a method as an output parameter, using the out keyword.  This indicates that the parameter is an output method.  For a reference type, this means that the method is expected to change the reference to point to a different object.

        public static void FindBallPlayingDog(out Dog fav)
        {
            fav = null;
            foreach (Dog d in AllDogs)
            {
                if (d.Motto.Contains("ball"))
                    fav = d;
            }
        }

When calling the method, we need to include the out keyword as a parameter modifier:

            Dog kirby = new Dog("Kirby");
            kirby.Motto = "Love chasing balls";

            Dog jack = new Dog("Jack");
            jack.Motto = "Sneak away when possible";

            Dog fav = jack;

            Dog.FindBallPlayingDog(out fav);   // Fav is now Kirby

#270 – Passing a Reference Type by Reference

When you pass a reference type by value to a method, you pass in a reference to the object.  The method can change the object, but can’t change the reference.

        public static void AnnotateMotto(Dog d)
        {
            // Change the dog's motto
            d.Motto = d.Motto + " while panting";
        }

You can also pass a reference type by reference, which means that the method can change not only the contents of the object pointed to, but change the reference, causing it to refer to a different object.

        public static void FindNewFavorite(ref Dog fav)
        {
            fav.Motto = "No longer the favorite";

            foreach (Dog d in AllDogs)
            {
                if (d.Motto.Contains("ball"))
                    fav = d;
            }
        }

Below is an example of calling this method.

            Dog kirby = new Dog("Kirby");
            kirby.Motto = "Retrieve balls";

            Dog jack = new Dog("Jack");
            jack.Motto = "Growl at people";

            Dog myFav = jack;
            Dog.FindNewFavorite(ref myFav);

            Console.WriteLine(myFav.Name);   // Kirby

#269 – Use ref Modifier on Parameters that Are Input/Output

You can use the ref modifier on a parameter to signal that it should be passed by reference.  Instead of passing in a copy of the current value, a reference to the variable is passed into the method.  The method can read or change the current value.  Changes to ref parameters are seen by the calling code when the method returns.

The ref modifier should be used for input/output parameters, when you want to pass data into the method and also receive updated data when the method returns.

        public static bool DoubleBigNumber(ref int aNumber)
        {
            bool didIt = false;

            if (aNumber > 1000)
            {
                aNumber *= 2;
                didIt = true;
            }

            return didIt;
        }

When calling the method, you use the ref modifier for any ref parameters.

            int myNumber = 1200;
            bool didit = NumberHelper.DoubleBigNumber(ref myNumber);

            Console.WriteLine(myNumber);        // Value now 2400

#268 – You Must Set the Value of All out Parameters Before Returning from a Method

You can use out parameters as a way of returning multiple data values from a method to its caller.  Because the intention of an output parameter is to return data to the caller, you must assign some value to every parameter marked as out before you can return from a method.  The compiler will enforce this rule.

In the example below, we’ve failed to set a value for the barkPhrase output parameter.

        public void GetDogVitals(out string fullName, out int age, out string barkPhrase)
        {
            fullName = string.Format("{0}, {1}", Name, Title);
            age = Age;
            //barkPhrase = BarkPhrase;
        }

When we try to compile the code, we’ll get an error telling us that we must assign a value to the barkPhrase output parameter before control leaves the method.

#267 – Passing Data Back from a Method Using out Parameters

If you want a method to return a single value, you can return that value as the result of the method.

        public int AgeInHumanYears()
        {
            return Age * 7;
        }

However, there might be times when you want to return more than one data item from a method.  You can do this with out parameters.  Putting the keyword out in front of a parameter tells the compiler that the caller will not pass data in, but the method will pass data out.

        public void GetDogVitals(out string fullName, out int age, out string barkPhrase)
        {
            fullName = string.Format("{0}, {1}", Name, Title);
            age = Age;
            barkPhrase = BarkPhrase;
        }

When you call the method, you also need to use the out keyword on the variables passed into the method.

            string hisFullName;
            int hisAge;
            string hisBark;
            kirby.GetDogVitals(out hisFullName, out hisAge, out hisBark);

#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.

#262 – Passing Data to a Method Using Parameters

You can pass one or more data values to a method using parameters.  A parameter in a method is just a variable, usable only within that method, that refers to a piece of data passed into the method.

Here’s an example of an instance method in a Dog class.  The Bark methods accepts a phrase for the dog to bark and the number of times that he should bark.  It then uses this data to do the barking.

        public void Bark(string barkPhrase, int numberBarks)
        {
            for (int i = 0; i < numberBarks; i++)
            {
                Console.WriteLine("{0} says: {1}", Name, barkPhrase);
            }
        }

We would call the Bark method on a Dog object as follows:

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            kirby.Bark("Wooferooni", 3);
            kirby.Bark("Rowf", 1);

And we’d get the following output:

The calling code invokes the method and passes a value for each parameter into the method.