#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