Question

For example, given a type param method i'm looking for something like the part in bold

void MyMethod< T >() {
if ( typeof(T).Implements( IMyInterface ) ) {

  //Do something   

else

  //Do something else 

}

Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)

Was it helpful?

Solution

Type.IsAssignableFrom

if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))
{
  // something
}
else
{
  // something else
}

OTHER TIPS

I think

if (typeof (IMyInterFace).IsAssignableFrom(typeof(T))

should also work: but i don't see an advantage...

Ï've just tried using

if( typeof(T).Equals(typeof(IMyInterface) ) 
     ...

And also works, but your answer seems more robust and was what I was looking for. Thanks!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top