Why do I need to set DateTime as Nullable like this?
DateTime? Err_Rpt_Tm = new DateTime?(DateTime.Now);
Console.WriteLine(Err_Rpt_Tm);
Because I find it odd that in Linqpad when I do this
DateTime Err_Rpt_Tm = new DateTime(DateTime.Now);
I get this error
The best overloaded method match for 'System.DateTime.DateTime(long)' has some invalid arguments
Argument 1: cannot convert from 'System.DateTime' to 'long'
DateTime?
is a short-hand for Nullable<DateTime>
. Let's look at documentation on MSDN. In constructors section the only available constructor is Nullable<T>(T)
. This explains why first part of your code compiles.
In second case you are trying to initialize DateTime
, and MSDN clearly states that there is no constructor, that accepts single parameter of type DateTime
. This is why you get a compile error in second case.
To fix the issue you can use much simpler form of initialization:
DateTime? Err_Rpt_Tm = DateTime.Now;
DateTime Err_Rpt_Tm2 = DateTime.Now;
This is possible because Nullable<T>
implements operators for converting nullable type to / from actual type.