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.
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
0
for Integer
, False
for Boolean
, DateTime.MinValue
for DateTime
, ... 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
DateTime?
(i.e. Nullable(Of DateTime)
). This is my preferred solution.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 = d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog