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.
Because the C# compiler simply looks at the types of
DateTime.NowandEmailMessage.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 theEmailMessage.Timestamp == nulland theTS = EmailMessage.Timestamp. Break 🙂I’ll add that your code normally is written this way:
using the ?? Operator This way the compiler knows that
TSisn’t nullable.