Day_Dreamer
Day_Dreamer

Reputation: 3373

using Nullable DateTime in C#

I wanted to assign null value to DateTime type in c#, so I used:

public DateTime? LockTime;

When LockTime is not assigned LockTime.Value contains null by default. I want to be able to change LockTime.Value to null after it has been assigned other value.

Upvotes: 2

Views: 1685

Answers (6)

Cesar Rojo
Cesar Rojo

Reputation: 1

You can define the variable this way:

private Nullable<DateTime> _assignedDate;  
_assignedDate = DateTime.Now;

and then assign a null value:

_assignedDate = null;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503974

No, if LockTime hasn't been assigned a value, it will be the nullable value by default - so LockTime.Value will throw an exception if you try to access it.

You can't assign null to LockTime.Value itself, firstly because it's read-only and secondly because the type of LockTime.Value is the non-nullable DateTime type.

However, you can set the value of the variable to be the null value in several different ways:

LockTime = null; // Probably the most idiomatic way
LockTime = new DateTime?();
LockTime = default(DateTime?);

Upvotes: 4

santa
santa

Reputation: 1003

     DateTime? nullableDT = null;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     nullableDT = DateTime.Now;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     nullableDT = null;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     /*
     False
     True    30.07.2010 11:17:59
     False
     */

Upvotes: 2

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158399

The Value porperty is readonly, so you can't assign a value to it. What you can do is to assign null to the LockTime field:

LockTime = null;

However, this will create a new DateTime? instance, so any other pieces of code having a reference to the original LockTime instance will not see this change. This is nothing strange, it's the same thing that would happen with a regular DateTime, so it's just something your code has to deal with gracefully.

Upvotes: 2

type_mismatch
type_mismatch

Reputation: 91

Have you tried LockTime = null?

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

You could assign null directly to the variable (the Value property is readonly and it cannot be assigned a value):

LockTime = null;

Upvotes: 4

Related Questions