Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What CLR do when compare T with null, and T is a struct?

Tags:

c#

clr

generics

private static void SaveOrRemove<T>(string key, T value)
{
    if (value == null)
    {
        Console.WriteLine("Remove: " + key);
    }

    //...
}

If I call passing 0 to value: SaveOrRemove("MyKey", 0), the condition value == null is false, then CLR dont make a value == default(T). What really happens?

like image 615
Felipe Pessoto Avatar asked Mar 19 '10 11:03

Felipe Pessoto


2 Answers

The JIT compiler basically removes any comparisons with null when T is a non-nullable value type, assuming them all to be false. (Nullable value types will compare with the null value for that type, which is probably what you expect.)

If you want it to compare to the default value, you could use:

if (EqualityComparer<T>.Default.Equals(value, default(T))
{
    ...
}
like image 112
Jon Skeet Avatar answered Nov 06 '22 13:11

Jon Skeet


Your question is answered in section 7.9.6 of the C# specification:

If an operand of a type parameter type T is compared to null, and the runtime type of T is a value type, the result of the comparison is false.

like image 39
Eric Lippert Avatar answered Nov 06 '22 15:11

Eric Lippert