#284 – Static Methods Can Call Instance Methods
March 28, 2011 Leave a comment
Static methods can call instance methods in a class–provided that they have access to a reference to an instance of the class.
In the example below, we have a static method of the Dog class that dumps out a bunch of information about every Dog instance in a collection of dogs passed to it.
public static void ListDogs(List<Dog> dogList, Cat cat)
{
foreach (Dog d in dogList)
{
string likes = d.LikesCat(cat) ? "Yes" : "No";
Console.WriteLine("{0}: {1} yrs old. Motto is [{2}]. Likes {3}? {4}",
d.Name,
d.Age,
d.Motto,
cat.Name,
likes);
}
}
Note that the static Dog method can also call an instance method of the Cat class.
Here’s how we might call this method:
List<Dog> dogs = new List<Dog>();
dogs.Add(new Dog("Kirby", 14, "Chase balls"));
dogs.Add(new Dog("Jack", 17, "Lounge around house"));
dogs.Add(new Dog("Ruby", 1, "Stare out window"));
Cat morris = new Cat("Morris");
Dog.ListDogs(dogs, morris);
