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 Doginstance in a collection of dogs passed to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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:
1 2 3 4 5 6 7 8 9 | 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); |
Output:


