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

C#.NetGenerics

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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)

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

try this:

if (typeof(T).IsValueType)

Solution 5 - C#

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTadeuszView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#HeinziView Answer on Stackoverflow
Solution 3 - C#Anton GogolevView Answer on Stackoverflow
Solution 4 - C#ojlovecdView Answer on Stackoverflow
Solution 5 - C#dbaView Answer on Stackoverflow