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


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

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 )

Connecting to %s

%d bloggers like this: