C # operator "==": compiler behavior with different structures

Code for illustration:

public struct MyStruct { public int SomeNumber; } public string DoSomethingWithMyStruct(MyStruct s) { if (s == null) return "this can't happen"; else return "ok"; } private string DoSomethingWithDateTime(DateTime s) { if (s == null) return "this can't happen"; // XX else return "ok"; } 

Now “DoSomethingWithStruct” cannot be compiled with: “Operator” == “cannot be applied to operands of type“ MyStruct "and" <null> ". This makes sense, since it makes no sense to try to map the link to a structure that is a value type.

OTOH, "DoSomethingWithDateTime" compiles, but with a compiler warning: "Inaccessible code detected" in a line labeled "XX". Now I assume that there is no compiler error, because the DateTime structure overloads the "==" operator. But how does the compiler know that the code is unreachable? For example, does it look inside the code that overloads the "==" operator? (This uses Visual Studio 2005, if that matters).

Note: I am more curious than any of the above. Usually I do not try to use "==" to compare structures and zeros.

EDIT: I will try to simplify my question - why compiling "DoSomethingWithDateTime" when "DoSomethingWithMyStruct" does not. Both arguments are structures.

+7
c #
source share
3 answers

He knows that a structure is never null ( Nullable<T> aside); this is enough to issue a warning.

A well-known compiler problem in this area that has arisen between the C # 2.0 compiler and the C # 3.0 compiler (and remains in the C # 4.0 compiler for now) [I'm not sure why you see it on VS2005, though]. The equality test does not warn unreachable code for custom structures with == / != Operators. DateTime has these operators; your structure is not - hence the difference.

This problem connected to the connection and was recently considered by the compiler team (who seek to fix it when an opportunity arises).

+4
source share

Since DateTime is a structure, it cannot be null. And there is no way to override the == operator for a structure so that the second parameter is null.

+2
source share

As Hun1Ahpu said, it can never be null.

However, you can provide your own == operator, which could take the object as a parameter type that would allow you to compile the above code.

Obviously, you will need to do something logical.

+2
source share

All Articles