#284 – Static Methods Can Call Instance Methods

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);

Output:

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #284 – Static Methods Can Call Instance Methods

  1. Pingback: #695 – Static Methods Can Access Static Members « 2,000 Things You Should Know About C#

Leave a comment