How to handle the null values for Datetime in c# [closed]

An object of type DateTime cannot be set to null. That is the reason why your code may be failing.

You can try using DateTime.MinValue to identify instances where a value has not been assigned.

Employee.CurrentLongTermIncentive.StartDate != DateTime.MinValue;

You can however configure DateTime to be nullable using the following Declaration.

DateTime? mydate = null;

if (mydate == null) Console.WriteLine("Is Null");
if (mydate.HasValue) Console.WriteLine("Not Null");

Note : the ? – this allows a non-nullable value to assigned as null.

You seem to be using DateTime? for start time, so try the following

if (!Employee.CurrentLongTermIncentive.StartDate.HasValue) {
  Employee.CurrentLongTermIncentive.StartDate = (DateTime?) DateTime.Parse(myDateString);
}

where myDateString is a string representing the date you want to assign.

Leave a Comment