Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast generic type parameter to a specific type in C#

Tags:

c#

.net

generics

If you need to cast a generic type parameter to a specific type, we can cast it to a object and do the casting like below:

void SomeMethod(T t) {     SomeClass obj2 = (SomeClass)(object)t; } 

Is there a better way to achieve this, rather than casting it to an object and then to a specific type?

Problem:

I have a generic function which accepts a generic type parameter, inside the function based on a type checking I do some operations like below:

    void SomeMethod(T t)     {         if (typeof(T).Equals(typeof(TypeA)))         {             TypeA = (TypeA)(object)t;             //Do some operation         }         else if (typeof(T).Equals(typeof(TypeB)))         {             TypeB = (TypeB)(object)t;             //Do some operation         }     } 
like image 712
Nipuna Avatar asked Aug 31 '16 08:08

Nipuna


People also ask

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.

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.

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 a generic type parameter?

Generic Methods 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.


2 Answers

You can use Convert.ChangeType

SomeClass obj2 = (SomeClass)Convert.ChangeType(t, typeof(SomeClass)); 

Although, keep in mind that this will throw an exception if a cast is invalid.

like image 189
Nikola.Lukovic Avatar answered Sep 17 '22 01:09

Nikola.Lukovic


Using as:

SomeClass obj2 = t as SomeClass; 

This would not throw an exception and t would be null if the cast fails.

I don't really know what you're trying to do, but I hope that you're not missing the point of Generics here.

If your intention is to restrict the method to type SomeClass and descendants:

void SomeMethod(T t)  where T : SomeClass 
like image 33
Zein Makki Avatar answered Sep 21 '22 01:09

Zein Makki