Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the `is` operator with Generics in C#

Tags:

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.

like image 514
Daniel A. White Avatar asked Feb 19 '10 20:02

Daniel A. White


People also ask

What is a generic operator?

An interface block can be used to define a generic operator. The only procedures allowed in the interface block are functions that can be referenced as defined operations. The initial line for such an interface block takes the following form: INTERFACE OPERATOR (op)

Can a generic class inherit?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

What are generics in C?

Generics are similar to templates in C++ but are different in implementation and capabilities. Generics introduces the concept of type parameters, because of which it is possible to create methods and classes that defers the framing of data type until the class or method is declared and is instantiated by client code.

Do generics use reflection?

Because the Common Language Runtime (CLR) has access to generic type information at run time, you can use reflection to obtain information about generic types in the same way as for non-generic types.


1 Answers

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

bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T)); 
like image 51
Fredrik Mörk Avatar answered Sep 24 '22 04:09

Fredrik Mörk