#454 – Return an Interface as a Return Value from a Method

In addition to passing interface variables into a method as parameters, you can also pass an interface back as the return value of a method.

In the example below, we define a method that looks through an array of objects and returns the first object found that implements the IMoo interface.

        static IMoo FindAMooer(object[] candidates)
        {
            IMoo theMooer = null;

            foreach (object candidate in candidates)
            {
                if (candidate is IMoo)
                {
                    theMooer = (IMoo)candidate;
                    break;    // stop looking
                }
            }

            return theMooer;
        }

We can then pass in any array of objects to this method and the method will find the first one that can moo.

            Cow bessie = new Cow("Bessie", 4);
            Dog spike = new Dog("Spike", 5);

            IMoo mooer = FindAMooer(new object[] { spike, 42, "Jude", bessie });
            mooer.Moo();

Advertisement