System.DateTime? vs System.DateTime

后端 未结 6 1127
心在旅途
心在旅途 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:31

    The Calendar control returns a Nullable (shorthand in C# is DateTime?) in its SelectedDate Property, since DateTime is a struct. The null value allows the Control to have a "no date selected" state. Thus, you'll need to check if the nullable has a value before you can use it.

    var nullable = myCalendarExtender.SelectedDate;
    var newSelectedDate = (nullable.HasValue) ? nullable.Value : SomeDefaultValue;
    

    EDIT: Even more concise, thanks to Josh's comment:

    var newSelectedDate = myCalendarExtender.SelectedDate ?? SomeDefaultValue;
    

    I like it!

提交回复
热议问题