System.DateTime? vs System.DateTime

后端 未结 6 1070
心在旅途
心在旅途 2021-02-05 02:53

I was writing to some code where I needed to read the date value from a Calendar control in my page (Ajax toolkit: calendar extender).

The code below:

6条回答
  •  攒了一身酷
    2021-02-05 03:27

    DateTime? is the same as Nullable That is: an instance of DateTime? can contain 'NULL', whereas an instance of DateTime does not. (This is true for all value - types since .NET 2.0. A Value type cannot contain NULL , but, as from .NET 2.0, nullable value types are supported via the Nullable construct (or the ? shorthand).

    You can get the value of DateTime? and put it in DateTime by doing this:

    DateTime? someNullableDate;
    DateTime myDate;
    
    if( someNullableDate.HasValue )
       myDate = someNullableDate.Value;
    

    Another, conciser way to get the value of a Nullable, is by using the null-coalescing operator:

    DateTime myDate = someNullableDate?? default(DateTime);
    

提交回复
热议问题