#448 – Use the is Operator to See if an Object Implements an Interface

We saw that we could use the as operator to cast an object to a variable of a particular interface type.  If the object’s type does not implement the interface, the as operator returns null.

            IMoo viaMoo = objSomething as IMoo;
            if (viaMoo != null)
                viaMoo.Moo();

You can also use the is operator to first check to see if an object’s class implements a particular interface.

        private static void MooIfYouCan(object mooCandidate)
        {
            IMoo viaMoo;
            if (mooCandidate is IMoo)
            {
                viaMoo = (IMoo)mooCandidate;
                viaMoo.Moo();
            }
        }

We can pass any object into this method and the IMoo.Moo method will be called only if the object implements the IMoo interface.

            Cow bossie = new Cow("Bossie", 12);
            object mooer = bossie;
            MooIfYouCan(mooer);

            mooer = new Dog("Bert", 5);
            MooIfYouCan(mooer);
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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: