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

c#, clr, generics

Solution

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))
{
    ...
}

Problem

``` 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?

Original source