Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime Variable

Tags:

c#

asp.net

I want to pass a null value for a DateTime variable in C#. The value should be stored in the database as null.

I've tried using Datetime.Minvalue, but that stores a default value. It has to be a null in database. How do I do that?


2 Answers

Use DateTime? as in

DateTime? foo = null;

That makes a nullable DateTime:

A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.

then when writing the value out, you can use the value like this:

if(foo == null)
{
   // Handle the null case
} 
else 
{
   // Handle the non-null case
}
like image 130
Daniel LeCheminant Avatar answered Jul 16 '26 07:07

Daniel LeCheminant


I agree with the nullable type answer, but when you go to write it to the database, you still need to test for null and convert it to DBNull.Value.

like image 31
jhale Avatar answered Jul 16 '26 05:07

jhale