Search code examples
vb.netdatetimenullnullable

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


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 possible to check if it is Nothing? For example:

Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing 

The second statement throws this error:

'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.

Solution

  • This is one of the biggest sources of confusion with VB.Net, IMO.

    Nothing in VB.Net is the equivalent of default in C#: the default value for the given type.

    • For value types, this is essentially the equivalent of 'zero': 0 for Integer, False for Boolean, DateTime.MinValue for DateTime, ...
    • For reference types, it is the null value (a reference that refers to, well, nothing).

    The statement d Is Nothing is therefore equivalent to d Is DateTime.MinValue, which obviously does not compile.

    Solutions: as others have said

    • Either use DateTime? (i.e. Nullable(Of DateTime)). This is my preferred solution.
    • Or use d = DateTime.MinValue or equivalently d = Nothing

    In the context of the original code, you could use:

    Dim d As DateTime? = Nothing
    Dim boolNotSet As Boolean = Not d.HasValue
    

    A more comprehensive explanation can be found on Anthony D. Green's blog