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?
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
If you call the GetGenericTypeDefinition method on a Type object that already represents a generic type definition, it returns the current Type. An array of generic types is not itself generic. In the C# code A<int>[] v; or the Visual Basic code Dim v() As A(Of Integer) , the type of variable v is not generic.
List is a reference type since it's a class.
There are two kinds of types in Visual Basic: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.
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 { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With