The behaviour described below is specific to .net-3.5 only
I just ran across the most astonishing behavior in the C# compiler;
I have the following code:
Guid g1 = Guid.Empty; bool b1= (g1 == null);
Well, Guid is not nullable therefore it can never be equal to null. The comparison i'm making in line 2 always returns false.
If you make the same thing for an integer, the compiler issues an warning saying the result will always be false:
int x=0; bool b2= (x==null);
My question is: Why does the compiler lets you compare a Guid to null?
According to my knowledge, it already knows the result is always false.
Is the built-in conversion done in such a way that the compiler does assume null is a possible value?
Am I missing anything here?
A Guid is a struct , those can't be null.
Empty is "{00000000-0000-0000-0000-000000000000}" which located the representation range of a guid, but we just marked is as Empty, so it is safe to use (someGuid ==Guid. Empty).
Mark is correct. Value types that define their own equality operators automatically get lifted-to-nullable versions defined as well, for free. The nullable equality operator that takes two nullable guids is applicable in this situation, will be called, and will always return false.
In C# 2, this produced a warning, but for some reason, this stopped producing a warning for guid-to-null but continues to produce a warning for int-to-null. I don't know why; I haven't had time to investigate yet.
I apologize for the error; I probably screwed up one of the warning-detection code paths when rewriting the nullable logic in C# 3. The addition of expression trees to the language majorly changed the order in which nullable arithmetic operations are realized; I made numerous mistakes moving that code around. It's some complicated code.
The comparison is valid because the compiler converts the Guid
to a Nullable<Guid>
and then it makes sense.
There is a bug report on the warning not being issued here.
See here here for a fuller explanation from Eric Lippert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With