Reputation:
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'
Upvotes: 0
Views: 328
Reputation: 148150
No DateTime constructor accepts DateTime object although it has constructor for long i.e. DateTime(long ticks) and error is suggesting that constructor to be used.
You can directly assign DateTime.Now to DateTime object and do not need a constructor for this.
DateTime Err_Rpt_Tm = DateTime.Now;
To assign to Nullable DateTime
DateTime? Err_Rpt_Tm = DateTime.Now;
Upvotes: 0
Reputation: 24916
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.
Upvotes: 2