2

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.

6 Answers 6

4

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?);
Sign up to request clarification or add additional context in comments.

Comments

4

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

LockTime = null;

Comments

2

Have you tried LockTime = null?

Comments

2

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.

Comments

2
     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
     */

Comments

0

You can define the variable this way:

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

and then assign a null value:

_assignedDate = null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.