Why can't I check if a 'DateTime' is 'Nothing'?

前端 未结 8 2039
天命终不由人
天命终不由人 2020-12-07 17:18

In VB.NET, is there a way to set a DateTime variable to \"not set\"? And why is it possible to set a DateTime to Nothing, but not<

相关标签:
8条回答
  • 2020-12-07 18:03

    DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue, or you can use Nullable(Of DateTime) instead.

    VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.

    See this question for an extensive discussion of value types vs. reference types.

    0 讨论(0)
  • 2020-12-07 18:10

    A way around this would be to use Object datatype instead:

    Private _myDate As Object
    Private Property MyDate As Date
        Get
            If IsNothing(_myDate) Then Return Nothing
            Return CDate(_myDate)
        End Get
        Set(value As Date)
            If date = Nothing Then
                _myDate = Nothing
                Return
            End If
            _myDate = value
         End Set
    End Property
    

    Then you can set the date to nothing like so:

    MyDate = Nothing
    Dim theDate As Date = MyDate
    If theDate = Nothing Then
        'date is nothing
    End If
    
    0 讨论(0)
提交回复
热议问题