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


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