views:

81

answers:

5

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.

+3  A: 

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

LockTime = null;
Darin Dimitrov
+1  A: 

Have you tried LockTime = null?

type_mismatch
+1  A: 

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.

Fredrik Mörk
+1  A: 
     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
     */
santa
oops... there are already answers :)
santa
+3  A: 

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?);
Jon Skeet