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.
1
2
3
4
5
6
7
8
9
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:


1
2
3
4
5
6
7
8
9
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