Quick Tip: Identifing the interfaces that an object implements

Quick Tip: Identifing the interfaces that an object implements

  • Comments 1
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:


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

-- DK

This posting is provided "AS IS" with no warranties, and confers no rights.