What Was I Thinking?

Follies & Foils of .NET Development

  Home  |   Contact  |   Syndication    |   Login
  41 Posts | 0 Stories | 97 Comments | 0 Trackbacks

News

Archives

Post Categories

Check These Out

Gurus

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;
}
posted on Wednesday, January 16, 2008 3:37 PM

Feedback

# re: QuickTip: How to determine if a type implements an interface 1/16/2008 4:26 PM Devin
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");
}




# re: QuickTip: How to determine if a type implements an interface 3/11/2009 9:43 AM Alex
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

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: