Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these tests for Nullable Type equivalent?

Tags:

c#

nullable

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 ?

like image 703
Guillaume Slashy Avatar asked Jan 16 '12 15:01

Guillaume Slashy


People also ask

How can you check a nullable variable for any type of value in C#?

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.

Which of the following can be used to test if a nullable variable has data?

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.

How do you check if something is nullable?

GetUnderlyingType() != null to identity if a type is nullable.


2 Answers

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;
}
like image 157
sehe Avatar answered Oct 13 '22 10:10

sehe


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;
}
like image 34
DmitryG Avatar answered Oct 13 '22 10:10

DmitryG