Reputation: 2323
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!
Upvotes: 4
Views: 222
Reputation: 3101
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.
}
Upvotes: 5
Reputation: 76500
You can explicitly check the generic type parameter using typeof
operator and Type.IsInterface
property.
void MyMethod<T>() {
bool isInterface = typeof(T).IsInterface;
}
Upvotes: 4
Reputation: 82335
Use the IsInterface
property of Type
..
public void DoCoolStuff<T>()
{
if(typeof(T).IsInterface)
{
//TODO: Cool stuff...
}
}
Upvotes: 9