How to check if a type parameter is really an interface

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!

+4
source share
3 answers

Use the IsInterface Type .. property.

 public void DoCoolStuff<T>() { if(typeof(T).IsInterface) { //TODO: Cool stuff... } } 
+9
source

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. } 
+5
source

You can explicitly test a type parameter with the typeof operator and Type.IsInterface .

 void MyMethod<T>() { bool isInterface = typeof(T).IsInterface; } 
+4
source

All Articles