Nullable DateTime variable

The data type DateTime in C# in non-nullable by default.We cannot assign null value. In that case we need to assign some minvalue for the DateTime variable. We can have a null value in DateTime by changing it into a Nullable. We will see the code snippet for this:

The below code throws the syntax error:

DateTime datevalue = null;

Because by default the C# DateTime data type is non nullable. This can be changed to nullable.

DateTime? denotes that the variable may hold the DateTime value or null value

Correct Syntax

private void button1_click(object sender, EventArgs e)
DateTime? dateValue = null;
private void TestMethod(DateTime? value)

The DateTime type is a value type and it is stored in a memory location. It cannot be assigned null instead we can use DateTime.MinValue. In some situations we may receive null value for our DateTime Parameter. In that case our code will throw an exception.

To avoid that we can declare a nullable DateTime?.DateTime? is a struct that wraps a DateTime struct which will be wrapped by a nullable type.

The variable can be declared as nullable when we are not sure whether the parameter may receives null or empty or not null.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: