Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
like image 488
Muleskinner Avatar asked May 03 '11 12:05

Muleskinner


People also ask

How do you check if a DateTime field is not null or empty?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.

How do you check if a date is empty?

Use the value property to check if an input type="date" is empty, e.g. if (! dateInput. value) {} . The value property stores the date formatted as YYYY-MM-DD or has an empty value if the user hasn't selected a date.

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

How check date is null in SQL?

SELECT * FROM employe WHERE date IS NOT NULL AND (date > ? AND date < ?) We first check if the date is null. If this condition its true, then it will check if the date is inside the range.


1 Answers

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.

  • 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 = d.HasValue 

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

like image 112
jeroenh Avatar answered Sep 28 '22 18:09

jeroenh