Quick Tip: Identifing the interfaces that an object implements

Have you ever wondered what type an object is?  How about what interfaces the object implements?  Using the .NET Framework and .NET Compact Framework, this information is very easy to determine.

The first thing we need to know about an object is it's type.  Every object, including Object, has a method called GetType().  For a given Object (obj), I get the Type (objType).

Type objType = obj.GetType();

GetType naturally returns a Type object.  The Type object is, to me, one of the most useful objects in .NET.  From the Type object, you can determine if the object is public, is a generic type, is abstract, and more.  You can also get the name of the type.

String objTypeName = objType.ToString();

When I called the above lines in a simple test application, the value of objTypeName was "System.Collections.Generic.List`1[System.String]", which tells me that obj is a List<String>.

Once we have the type of our object, we can get the list of interfaces implemented by the object (List<String>).

Type[] objInterfaces = objType.GetInterfaces();

To continue my example, by iterating over objInterfaces I see that List<String> implements:

System.Collections.Generic.IList`1[System.String]System.Collections.Generic.ICollection`1[System.String]System.Collections.Generic.IEnumerable`1[System.String]System.Collections.IListSystem.Collections.ICollectionSystem.Collections.IEnumerable

Knowing the interfaces implemented by a type can be useful in a variety of applications; from diagnostic tools to applications supporting plugins and more. 

Enjoy!
-- DK

Disclaimer(s):
This posting is provided "AS IS" with no warranties, and confers no rights.