Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking type parameter of a generic method in C#

Is it possible to do something like this in C#:

public void DoSomething<T>(T t)   {     if (T is MyClass)     {         MyClass mc = (MyClass)t          ...     }     else if (T is List<MyClass>)     {         List<MyClass> lmc = (List<MyClass>)t         ...     } } 
like image 875
synergetic Avatar asked Jan 05 '10 06:01

synergetic


People also ask

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

What is type parameters in generics?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

Where is generic type constraint?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.


1 Answers

Yes:

if (typeof(T) == typeof(MyClass)) {     MyClass mc = (MyClass)(object) t; } else if (typeof(T) == typeof(List<MyClass>)) {     List<MyClass> lmc = (List<MyClass>)(object) t; } 

It's slightly odd that you need to go via a cast to object, but that's just the way that generics work - there aren't as many conversions from a generic type as you might expect.

Of course another alternative is to use the normal execution time check:

MyClass mc = t as MyClass; if (mc != null) {     // ... } else {     List<MyClass> lmc = t as List<MyClass>;     if (lmc != null)     {         // ...     } } 

That will behave differently to the first code block if t is null, of course.

I would try to avoid this kind of code where possible, however - it can be necessary sometimes, but the idea of generic methods is to be able to write generic code which works the same way for any type.

like image 123
Jon Skeet Avatar answered Sep 30 '22 06:09

Jon Skeet