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?
You can use the
typeofoperator with generic types, sotypeof(T)will get theTypereference corresponding toT, and then use theIsValueTypeproperty:Or if you want to include nullable value types as if they were reference types: