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 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)
[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 {
...
}
Type.IsValueType
tells, naturally, if Type
is a value type. Hence, typeof(T).IsValueType
.
try this:
if (typeof(T).IsValueType)
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)