Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether T is a value type or reference class in generic?

Tags:

c#

.net

generics

I have a generic method behavior of which depends on T is reference type or value type. It looks so:

T SomeGenericMethod <T> (T obj) {   if (T is class) //What condition I must write in the brackets?    //to do one stuff   else //if T is a value type like struct, int, enum and etc.    //to do another stuff } 

I can't duplicate this method like:

T SomeGenericMethod <T> (T obj) where T : class {  //Do one stuff }  T SomeGenericMethod <T> (T obj) where T : struct {  //Do another stuff } 

because their signatures are equal. Can anyone help me?

like image 813
Vasya Avatar asked Sep 28 '11 08:09

Vasya


People also ask

How do you determine what type a generic parameter T is?

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.

How do you find the type of generic object?

If you call the GetGenericTypeDefinition method on a Type object that already represents a generic type definition, it returns the current Type. An array of generic types is not itself generic. In the C# code A<int>[] v; or the Visual Basic code Dim v() As A(Of Integer) , the type of variable v is not generic.

Is a generic list a reference type?

List is a reference type since it's a class.

What is the main difference between a value type and a reference type?

There are two kinds of types in Visual Basic: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.


2 Answers

You can use the typeof operator with generic types, so typeof(T) will get the Type reference corresponding to T, and then use the IsValueType property:

if (typeof(T).IsValueType) 

Or if you want to include nullable value types as if they were reference types:

// Only true if T is a reference type or nullable value type if (default(T) == null) 
like image 112
Jon Skeet Avatar answered Sep 20 '22 21:09

Jon Skeet


[The following answer does not check the static type of T but the dynamic type of obj. This is not exactly what you asked for, but since it might be useful for your problem anyway, I'll keep this answer for reference.]

All value types (and only those) derive from System.ValueType. Thus, the following condition can be used:

if (obj is ValueType) {     ... } else {     ... } 
like image 38
Heinzi Avatar answered Sep 20 '22 21:09

Heinzi