質問

Why is integer == null a valid boolean expression in C#, if integer (variable of type int) is not nullable? (I'm not against it, in fact I like it, but I didn't know it was possible)

役に立ちましたか?

解決

Although int itself is non-nullable, there's an implicit conversion to int?, which is nullable.

At that point, if the struct declares an == operator with the same type on both sides, then that's lifted to work with nullable types too.

So this doesn't compile:

public struct Foo {}

class Test
{
    static void Main()
    {
        Foo x = new Foo();
        if (x == null)
        {
            ...
        }
    }
}

... but if you give Foo some operators, it does compile, and without a warning:

public struct Foo
{
    public static bool operator ==(Foo x, Foo y) { return true; }
    public static bool operator !=(Foo x, Foo y) { return false; }
    public override bool Equals(object x) { return false; }
    public override int GetHashCode() { return 0; }
}

The operator invocation isn't included in the compiled code, because the compiler knows that the RHS is null.

So code of the form above (where Foo can be replaced by any non-nullable struct) has one of three outcomes with the MS C# 5 compiler:

  • Warning CS0472 (e.g. with int)
  • Error CS0019 (custom types which don't overload ==)
  • Clean compilation (custom types which overload ==, including Guid and DateTime)

It's not clear to me why the compiler treats some "known" types differently to normal structs though. EDIT: As noted by Eric in comments, this is a known bug in the C# compiler, which is hopefully fixed in Roslyn.

他のヒント

As Ed mentions there's a warning, but the warning alludes to the reason: int can be auto-casted to int?, and null is a valid value for a variable of type int?.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top