开发者

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

开发者 https://www.devze.com 2022-12-23 17:15 出处:网络
private static void SaveOrRemove<T>(string key, T value) { if (value == null) { Console.WriteLine(\"Remove: \" + key);
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, th开发者_如何学Goen 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 want default(T) you have to say it, not null which has its own meaning. If you want the ability to actually pass in a null in place of a value type, you should use Nullable<T> instead.

So, your code would become:

private static void SaveOrRemove<T>(string key, Nullable<T> value)
{
    if (!value.HasValue()) // is null
    {
        Console.WriteLine("Remove: " + key);
    }
    else
    {
        T val = value.Value;
        // ...
    }
}

Note that Nullable<T> is only useful with value types (structs, "builtins" other than string); for reference types you can't use it anyway.

MSDN link

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号