System.DateTime? vs System.DateTime

后端 未结 6 1076
心在旅途
心在旅途 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:25
    var Endtime = DateTime.Now();
    DateTime startTime = item.REPORT_TIME.HasValue ? item.REPORT_TIME.Value : Endtime;
    

    Means: the type of item.item.REPORT_TIME is system.DateTime?
    howerver the type of startTime is system.DateTime; so the code can changed it like

    `var Endtime=DateTime.Now; var startTime=item.REPORT_TIME.HasValue?Convert.ToDateTime(item.REPORT_TIME.HasValue):Endtime

    `

    0 讨论(0)
  • 2021-02-05 03:27

    DateTime? is the same as Nullable<DateTime> 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<T> 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);
    
    0 讨论(0)
  • 2021-02-05 03:27

    You can use the ?? operator to work with nullables in a very concise way in C#. See my comment on Travis's answer for a shorter way of expressing the "if not null then use it else use some default value" concept. They both do the same thing.

    0 讨论(0)
  • 2021-02-05 03:31

    The Calendar control returns a Nullable<DateTime> (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!

    0 讨论(0)
  • 2021-02-05 03:42

    A much better solution and IMO the best feature of all with the nullable class

    DateTime newSelectedDate = myCalendarExtender.SelectedDate.GetValueOrDefault();
    
    0 讨论(0)
  • 2021-02-05 03:46

    ? means that the type is nullable. For details, see e.g. MSDN

    Nullable is a compiler-supported wrapper around value types that allows value types to become null.

    To access the DateTime value, you need to do the following:

    DateTime? dateOrNull = myCalendarExtender.SelectedDate;
    if (dateOrNull != null)
    {
        DateTime newSelectedDate = dateOrNull.Value;
    }
    
    0 讨论(0)
提交回复
热议问题