Can a DateTime be null? [duplicate]

2019-04-18 12:16发布

Possible Duplicate:
DateTime “null” value

is it possible to set datetime object to null?

6条回答
beautiful°
2楼-- · 2019-04-18 12:48

Normally DateTime cannot be null, since is a Value Type, but using the nullable operator introduced in C# 2, you can accomplish this

查看更多
【Aperson】
3楼-- · 2019-04-18 12:52

DateTime is a value type, which, just like int and double, has no meaningful null value.

In VB.NET, you can write this:

Dim d As DateTime = Nothing

But all this does is to set d to the default DateTime value. In C# the equivalent code would be this:

DateTime d = default(DateTime);

...which is equivalent to DateTime.MinValue.

That said, there is the Nullable<T> type, which is used to provide a null value for any value type T. The shorthand for Nullable<DateTime> in C# is DateTime?.

查看更多
Emotional °昔
4楼-- · 2019-04-18 12:59
DateTime? myDate = null;

The question mark will give you a nullable type. The one that can either be set to its native value or to null.

DateTime itself is a value type. It cannot be null.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-04-18 13:01

Nope, you cannot for DateTime is a value type.

You might want to look at Nullable<DateTime> though (or DateTime? in short)

查看更多
forever°为你锁心
6楼-- · 2019-04-18 13:05

No -- DateTime is a struct in C# and structs (value types) can not be null.

You can, however, use Nullable<DateTime>.

查看更多
SAY GOODBYE
7楼-- · 2019-04-18 13:06

No, its a structure not a class. Either make it a nullable type, e.g. System.DateTime? myValue; or use the System.DateTime.MinValue as a sentinel.

查看更多
登录 后发表回答