What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

QuickTip: How to determine if a type implements an interface

This is the functional equivalent of  a "type is anothertype" but for interfaces:

public static bool TypeImplementsInterface(Type type, Type interfaceType)
{
    string interfaceFullName = interfaceType.FullName;
    return type.GetInterface(interfaceFullName) != null;
}

Print | posted on Wednesday, January 16, 2008 3:37 PM | Filed Under [ Visual Studio ]

Feedback

Gravatar

# re: QuickTip: How to determine if a type implements an interface

You can actually use the is keyword to determine if a type has implemented an Interface. The snippet below tests to see whether the ArrayList is an IEnumerable:

ArrayList foo = new ArrayList();
if (foo is IEnumerable)
{
MessageBox.Show("yup");
}

You can apply the same test to see if a type is derived from another type. In this snippet I am testing to see if the Windows Form (this) is a ControlContainer. This is really a Form object, but Form derives from ControlContainer:

if (this is ContainerControl)
{
MessageBox.Show("yup");
}


1/16/2008 4:26 PM | Devin
Gravatar

# re: QuickTip: How to determine if a type implements an interface

Usage of the keyword is requires the comparison of the instance of the object with a Type as precisely in your example. But doesn't not allow for comparison of Type with Type e.g

if (ArrayList is IEnumerable) { } : wrong

hence usage of first example is required
3/11/2009 9:43 AM | Alex
Gravatar

# re: QuickTip: How to determine if a type implements an interface

There's a better way -- I would recommend you check this out: http://bit.ly/ccza8B
7/27/2010 6:06 PM | Brad Heller
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: