3

Possible Duplicate:
C# okay with comparing value types to null

Consider the following code with the TimeSpan, which is a struct:

// will not compile - illegal
TimeSpan ts = null;  

However, the following code does compile and is legal, though the expression is always false:

if (ts == null)
    Console.WriteLine("this line will never be hit");

Can someone tell me why it's invalid to set a struct to a NULL, but it's ok to compare it to one?

Community
  • 1
  • 1
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • http://stackoverflow.com/questions/2022425/comparing-structs-to-null, http://stackoverflow.com/questions/648115/how-can-an-object-not-be-compared-to-null, http://stackoverflow.com/questions/1225949/why-can-timespan-and-guid-structs-be-compared-to-null, http://stackoverflow.com/questions/1972262/c-sharp-okay-with-comparing-value-types-to-null – nawfal Apr 09 '12 at 23:44
  • If you couldn't compare structs to null, what would you do with Nullable? – Anthony Pegram Apr 09 '12 at 23:46
  • @AnthonyPegram: Better question is; how would you implement `Nullable` as a `struct`? (of course, you couldn't). `Nullable` could of course be implemented as a reference type – Ed S. Apr 10 '12 at 00:02
  • 1
    @EdS. but `Nullable` *is* a struct. – phoog Apr 10 '12 at 00:17
  • @phoog: Right, that's what I was getting at :) – Ed S. Apr 10 '12 at 17:01

2 Answers2

7

It's still legal because you can overload the == operator for structs.

struct AmNull {
    public static bool operator ==(AmNull a, object b) {
        return b == null;
    }

    public static bool operator !=(AmNull a, object b) {
        return b != null;
    }
}

...

Console.WriteLine(new AmNull() == null); // True
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 3
    @AngrHacker: I think you should chose this response as the accepted answer. It covers my response but expands upon it to explain why this behavior is present. – Ed S. Apr 10 '12 at 17:00
3

Fails to compile for me:

struct Foo { }

class Program
{       
    static void Main( string[] args )
    {
        var f = new Foo();
        if( f == null ) { }
    }
}

Error 1 Operator '==' cannot be applied to operands of type 'ConsoleApplication3.Foo' and 'null'

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • @AngryHacker: It's because `TimeSpan` overloads the `==` operator (I didn't catch that at first). My point is that your question "Why is comparing a struct to NULL legal in C#?" isn't complete; you can't, unless you overload the equality operator to accept it. minitech has a better response. – Ed S. Apr 09 '12 at 23:45