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