Is Nullable<int> a “Predefined value type” - Or how does Equals() and == work here?

时间秒杀一切 提交于 2019-12-03 04:24:51

In C#, there's a concept called "Lifted Operators", described in section 7.3.7 of the language specification (Version 5 download):

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following

And specifically:

For the equality operators

==  !=

a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

So, since there's an == operator defined between ints, there's also one defined for int?s

If you compare those values it will actually call the Nullable<T>.Equals method, since both values are nullable ints.

Nullable<T>.Equals will eventually call the == compare keyword of int, if both values are not null. So in the end, it will indeed check the values.

The code from the Equals method shows this well:

public override bool Equals(object other)
{
    if (!this.HasValue)
    {
        return (other == null);
    }
    if (other == null)
    {
        return false;
    }
    return this.value.Equals(other);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!