Search code examples
c#datetimenullable

Nullable DateTime setting it getting invalid argument with cannot convert to long


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'

  1. DateTime.Now is never going to be null, so I don't understand the need for nullable DateTime?
  2. convert System.DateTime to long??? I'm explicitly setting DateTime variable "Err_Rpt_Tm"

Solution

  • 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.