tags:

views:

74

answers:

3

Hi all,

I have a generic function and I want to check whether the type parameter is an interface. Is there anyway to do that? Thanks in advance!

+7  A: 

Use the IsInterface property of Type..

public void DoCoolStuff<T>()
{
    if(typeof(T).IsInterface)
    {
        //TODO: Cool stuff...
    }
}
Quintin Robinson
Like shooting fish in a barrel!
Dave White
+4  A: 

You can explicitly check the generic type parameter using typeof operator and Type.IsInterface property.

void MyMethod<T>() {
  bool isInterface = typeof(T).IsInterface;
}
Igor Zevaka
+4  A: 

If you want to constrain your generic method so that the type parameter can only be a type that implements some specific interface and nothing else, then you should do the following:

void YourGenericMethod<T>() where T : IYourInterface {
    // Do stuff. T is IYourInterface.
}
Rich
+1 I didn't think about it, but this might be the actual problem OP is trying to solve.
Igor Zevaka
This is the best practice
Martin Murphy