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?
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?
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
}
You could use DateTime?
values type. It can have null
values but otherwise it's completely the same as DateTime
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.