Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guid == null should not be allowed by the compiler

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?

like image 979
Luis Filipe Avatar asked Feb 01 '10 15:02

Luis Filipe


People also ask

Can a Guid be null?

A Guid is a struct , those can't be null.

Is Empty Guid valid?

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


2 Answers

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.

like image 60
Eric Lippert Avatar answered Oct 05 '22 17:10

Eric Lippert


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.

like image 39
Mark Byers Avatar answered Oct 05 '22 19:10

Mark Byers