#448 – Use the is Operator to See if an Object Implements an Interface
November 4, 2011 Leave a comment
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);