#449 – You Can Pass an Interface Variable to a Method

You can include a parameter in a method whose type is an interface, allowing you to pass interface variables into the method.

For example, we can write a method that takes variable of type IMoo.

        private static void DoSomeMooing(IMoo mooer)
        {
            for (int i = 0; i < 3; i++)
                mooer.Moo();
        }

We can now pass into this method a reference to any object that implements IMoo.

We might pass in an interface variable:

            Cow bessie = new Cow("Bessie", 4);
            IMoo viaMoo = bessie;
            DoSomeMooing(viaMoo);


We could also just pass an instance of a Cow directly into the method.  It will be implicitly cast to a reference of type IMoo and so the DoSomeMooing method will have access only to the members of Cow that are part of IMoo.

            Cow bessie = new Cow("Bessie", 4);

            DoSomeMooing(bessie);
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 #449 – You Can Pass an Interface Variable to a Method

  1. Pingback: #454 – Return an Interface as a Return Value from a Method « 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: