开发者

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.Val开发者_JAVA技巧ue to null after it has been assigned other value.


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


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

LockTime = null;


Have you tried LockTime = null?


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.


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


You can define the variable this way:

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

and then assign a null value:

_assignedDate = null;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜