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

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