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?
try this:
[The following answer does not check the static type of
T
but the dynamic type ofobj
. 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:I'm late to the party, but I just stumbled on this. So as of determining if it's a Reference-Type,
respectively
could work (.net 4.7+ , not checked on former Versions)
Type.IsValueType
tells, naturally, ifType
is a value type. Hence,typeof(T).IsValueType
.You can use the
typeof
operator with generic types, sotypeof(T)
will get theType
reference corresponding toT
, and then use theIsValueType
property:Or if you want to include nullable value types as if they were reference types: