#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:

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: