views:

293

answers:

6

I want to do something like this

class SomeClass<T>
{
   SomeClass()
   {
        bool IsInterface = T is ISomeInterface;
   }
}

What is the best way to something like this?

Note: I am not looking to constrain T with a where, but I would like my code to be aware of what types of interfaces T implements. I would prefer that I dont have to construct a T.

+14  A: 

I don't think you can use the is operator for this. But you can use IsAssignableFrom:

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
Fredrik Mörk
+1  A: 

I believe the best you can do it:

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
James Curran
+4  A: 
Asad Butt
A: 

You could try doing something like

Type Ttype = typeof(T);

That will give you the full power of the Type class, which has functions like "FindInterfaces".

GWLlosa
+2  A: 

You can use IsAssignableFrom:

  class SomeClass<T>
  {
     SomeClass()
     {
        bool IsIComparable = typeof(IComparable).IsAssignableFrom(typeof(T));
     }
  } 
SwDevMan81
+2  A: 
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T))
Daok