Tadeusz
Tadeusz

Reputation: 6903

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

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?

Upvotes: 65

Views: 28001

Answers (5)

dba
dba

Reputation: 1195

I'm late to the party, but I just stumbled on this. So as of determining if it's a Reference-Type,

typeof(T).IsClass

respectively

obj.GetType().IsClass

could work (.net 4.7+ , not checked on former Versions)

Upvotes: 5

Heinzi
Heinzi

Reputation: 172438

[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 {
    ...
}

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1503130

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)

Upvotes: 116

ojlovecd
ojlovecd

Reputation: 4902

try this:

if (typeof(T).IsValueType)

Upvotes: 6

Anton Gogolev
Anton Gogolev

Reputation: 115857

Type.IsValueType tells, naturally, if Type is a value type. Hence, typeof(T).IsValueType.

Upvotes: 7

Related Questions