[c#] How to set DateTime to null

Using C#. I have a string dateTimeEnd.

If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd of type

public Nullable<System.DateTime> DateTimeEnd { get; set; }

If dateTimeEnd is null or empty I need eventCustom.DateTimeEnd set to null.

I am trying to achieve this using the following code but I get always null for eventCustom.DateTimeEnd.

Could you please help me out to define what is wrong in my code?

   DateTime? dateTimeEndResult;
     if (!string.IsNullOrWhiteSpace(dateTimeEnd))
        dateTimeEndResult = DateTime.Parse(dateTimeEnd);


eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;

This question is related to c# entity-framework

The answer is


You can write DateTime? newdate = null;


DateTime is a non-nullable value type

DateTime? newdate = null;

You can use a Nullable<DateTime>

c# Nullable Datetime


This should work:

if (!string.IsNullOrWhiteSpace(dateTimeEnd))
    eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
    eventCustom.DateTimeEnd = null;

Note that this will throw an exception if the string is not in the correct format.


Now, I can't use DateTime?, I am using DBNull.Value for all data types. It works great.

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
  ? DBNull.Value
  : DateTime.Parse(dateTimeEnd);

This line:

eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;

is same as:

eventCustom.DateTimeEnd = dateTimeEndResult = (true ? (DateTime?)null : dateTimeEndResult);

because the conditional operator ? has a higher precedence than the assignment operator =. That's why you always get null for eventCustom.DateTimeEnd. (MSDN Ref)