How do I set a nullable DateTime to null in VB.NET?

后端 未结 5 1183
有刺的猬
有刺的猬 2020-12-10 11:58

I am trying to set up a date range filter on my UI, with checkboxes to say whether a DateTimePicker\'s value should be used, e.g.

Dim fromDate As DateTime? =         


        
5条回答
  •  攒了一身酷
    2020-12-10 12:08

    The issue is that it's examining the right-hand side of this assignment first, and deciding that it is of type DateTime (no ?). Then performing the assignment.

    This will work:

    Dim fromDate As DateTime? = If(fromDatePicker.Checked, _
                                   fromDatePicker.Value, _
                                   CType(Nothing, DateTime?))
    

    Because it forces the right-hand side's type to be DateTime?.

    As I said in my comment, Nothing can be more akin to C#'s default(T) rather than null:

    Nothing represents the default value of a data type. The default value depends on whether the variable is of a value type or of a reference type.

提交回复
热议问题