Here is the condition I used to detect if we are dealing with a Nullable Type :
System.Nullable.GetUnderlyingType(itemType) != null
and here the code of my teammate :
itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(Nullable<>)
We actually didnt find a case where one will return true
and the other false
(or vice-versa) but are these 2 snippets strictly equivalent ?
You cannot directly access the value of the Nullable type. You have to use GetValueOrDefault() method to get an original assigned value if it is not null. You will get the default value if it is null.
The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and != operators with a nullable type.
GetUnderlyingType() != null to identity if a type is nullable.
From MSDN for Nullable.GetUnderlyingType Method:
The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null.
So, yes it is safe to use the former version.
Decompiled from GetUnderlyingType:
public static Type GetUnderlyingType(Type nullableType)
{
if (nullableType == null)
throw new ArgumentNullException("nullableType");
Type type = (Type) null;
if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition && nullableType.GetGenericTypeDefinition() == typeof (Nullable<>))
type = nullableType.GetGenericArguments()[0];
return type;
}
These 2 snippets are not fully equivalen.
Here is the test case that returns a different values for each snippets:
Type t = typeof(Nullable<>);
bool c1 = Nullable.GetUnderlyingType(t) != null; //false
bool c2 = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>); //true
Thus the Nullable.GetUnderlyingType method more safe, because it's implementation already include this test case checking:
public static Type GetUnderlyingType(Type nullableType) {
if (nullableType == null)
throw new ArgumentNullException("nullableType");
Type type = null;
if ((nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition)
&& (nullableType.GetGenericTypeDefinition() == typeof(Nullable<>))) {
type = nullableType.GetGenericArguments()[0];
}
return type;
}
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