How does the C # Visual Studio Compiler consider / NULL structure comparisons?

We just came across some bad code like this in our C # .net 4 codebase

DateTime myDate = someValue; If (myDate==Null) Do Something 

It occurred to us that this condition would never happen.

How does the compiler handle these odd comparisons of structures?

We were initially surprised that it would compile ... but rationalized it in the sense that you could certainly have a constant comparison, for example:

 If(1==2) 

Which will also never allow true ... but in this case the compiler can easily say that they are constants. Does it optimize or minimize comparisons with a null value?

+4
source share
1 answer

I pierced this in LinqPad:

 var t = new DateTime(); t.Dump(); (t == null).Dump(); 

And got the following:

 IL_0000: ldloca.s 00 IL_0002: initobj System.DateTime IL_0008: ldloc.0 IL_0009: call LINQPad.Extensions.Dump IL_000E: pop IL_000F: ldc.i4.0 IL_0010: call LINQPad.Extensions.Dump 

So yes, the compiler compiles it the same way:

 var t = new DateTime(); t.Dump(); (false).Dump(); 

I wonder if I create my own structure ( TestStruct ) and try this:

 TestStruct t; (t == null).Dump(); 

... the compiler complains that I cannot perform an equal comparison between TestSruct and null .

Update

In a comment, Paolo points to another StackOverflow post reporting this latest phenomenon. Apparently, overloading the == and != Operators, the type of the value is automatically converted from t == null to (Nullable<TestClass>)t == (Nullable<TestClass>)null . If you did not overload these statements, this implicit conversion does not make sense, so you will receive an error message.

+7
source

Source: https://habr.com/ru/post/1397919/


All Articles