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.
1
2
3
| 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.
1
2
3
4
5
6
7
8
9
| 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 theIMoo interface.
1
2
3
4
5
6
| Cow bossie = new Cow("Bossie", 12);object mooer = bossie;MooIfYouCan(mooer);mooer = new Dog("Bert", 5);MooIfYouCan(mooer); |

