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

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

Leave a comment