Daniel A. White
Daniel A. White

Reputation: 190907

Using the `is` operator with Generics in C#

I want to do something like this:

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

What is the best way for 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 don't have to construct a T.

Upvotes: 27

Views: 11407

Answers (6)

Asad
Asad

Reputation: 21928

should use following instead

 bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));

is operator

is operator is used to check whether the run-time type of an object is compatible with a given type.

An expression where the use of is conforms to the syntax, evaluates to true, if both of the following conditions are met:

  • expression is not null.
  • expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception. For more information, see 7.6.6 Cast expressions.

References

Upvotes: 9

Patrick Desjardins
Patrick Desjardins

Reputation: 140753

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T))

Upvotes: 1

SwDevMan81
SwDevMan81

Reputation: 49978

You can use IsAssignableFrom:

  class SomeClass<T>
  {
     SomeClass()
     {
        bool IsIComparable = typeof(IComparable).IsAssignableFrom(typeof(T));
     }
  } 

Upvotes: 1

GWLlosa
GWLlosa

Reputation: 24403

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".

Upvotes: 0

James Curran
James Curran

Reputation: 103485

I believe the best you can do it:

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));

Upvotes: 0

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

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

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));

Upvotes: 33

Related Questions