views:

120

answers:

3

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 ;)

+5  A: 

Type.IsAssignableFrom

if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))
{
  // something
}
else
{
  // something else
}
Jonathan
+1  A: 

I think

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

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

MADMap
A: 

Ï'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!

Ricky AH
It does? it should only work of T is specifically IMyInterface
James Curran
It worked for me in my specific case, but the behavior is the one you describe: it doesn't work if you want to know if an object implements IMyInterface, but to assert that the type T is an IMyInterface.Thanks for the correction!
Ricky AH