Q:

The return type of a C# conditional operator

I have an object called EmailMessage, which has a nullable System.DateTime field called Timestamp.  In my C# code I have the following line:
var TS = EmailMessage.Timestamp == null ? System.DateTime.Now : EmailMessage.Timestamp;

Why does .NET 4 infer the data type of TS to be System.DateTime? rather than System.DateTime  (In other words, why does .NET 4 think TS is nullable?)  It seems really obvious to me that TS is decidedly not nullable.
Thanks in advance for your help.

A:

Because the C# compiler simply looks at the types of DateTime.Now and EmailMessage.Timestamp :-)
And I'll tell you something: I could break your assumption. Let's say that there are two threads. One thread has your code, the other thread has EmailMessage.Timestamp = null. The other thread executes between the EmailMessage.Timestamp == null and the TS = EmailMessage.Timestamp. Break :-)
I'll add that your code normally is written this way:
var TS = EmailMessage.Timestamp ?? System.DateTime.Now;

using the ?? Operator This way the compiler knows that TS isn't nullable.

