I have a generic function and I want to check if a type parameter is an interface. Is there any way to do this? Thanks in advance!
Use the IsInterface Type .. property.
IsInterface
Type
public void DoCoolStuff<T>() { if(typeof(T).IsInterface) { //TODO: Cool stuff... } }
If you want to limit your general method so that the type parameter can only be a type that implements any particular interface and nothing more, then you should do the following:
void YourGenericMethod<T>() where T : IYourInterface { // Do stuff. T is IYourInterface. }
You can explicitly test a type parameter with the typeof operator and Type.IsInterface .
typeof
Type.IsInterface
void MyMethod<T>() { bool isInterface = typeof(T).IsInterface; }