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 ofdefault(T)
in C#: the default value for the given type.0
forInteger
,False
forBoolean
,DateTime.MinValue
forDateTime
, ...null
value (a reference that refers to, well, nothing).The statement
d Is Nothing
is therefore equivalent tod 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 equivalentlyd = Nothing
In the context of the original code, you could use:
DateTime is a value type, which means it always has some value.
It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".
If you want a DateTime that can take the value Nothing, use a Nullable DateTime.
In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!
You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:
End Class
'in Main():
Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.
A way around this would be to use Object datatype instead:
Then you can set the date to nothing like so:
You can also use below just simple to check:
It will check that the startDate variable of DateTime datatype is null or not.
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 useNullable(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.