Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is integer == null a valid boolean expression in C#?

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)

like image 641
Guillermo Gutiérrez Avatar asked Jun 18 '13 21:06

Guillermo Gutiérrez


2 Answers

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.

like image 141
Jon Skeet Avatar answered Sep 18 '22 16:09

Jon Skeet


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

like image 40
Shlomo Avatar answered Sep 21 '22 16:09

Shlomo