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