Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET - Create Nullable(Of T) with HasValue = False

I'm working against a SQL Server database that regularly has DateTime columns that can be null. I'm using LINQ to SQL to connect my WinForms (VB.NET) program to the data.

I've extended some of the LINQ objects and added a couple of Nullable(Of DateTime) properties. Basically, I'm calculating whether a particular value exists. The value is a DateTime. If it doesn't exist, I want to create a Nullable(Of DateTime) object (structure, whatever) with the HasValue property set to False.

I did some research, and apparently, the New constructor on a Nullable(Of T) creates one with HasValue set to True.

Two questions:

  1. Why is this? Since the Nullable(Of T) structure was created specifically for this type of situation, why would the default behavior be HasValue = True?
  2. What's the best way to initialize a Nullable(Of T) to actually be null?

Thanks!

like image 377
mbm29414 Avatar asked Feb 05 '26 07:02

mbm29414


2 Answers

If you're supplying a value to the Nullable constructor then it will have the given value, which would result in the scenario you're describing where HasValue is true.

To declare a nullable with a HasValue of false you can take either of these approaches:

Dim x As Nullable(Of DateTime)
Dim y As DateTime?

However, if you're using the constructor and supplying a value, the nullable struct won't have a null value, and it's HasValue would be true:

Dim z As New Nullable(Of DateTime)(DateTime.Now)
like image 193
Ahmad Mageed Avatar answered Feb 09 '26 09:02

Ahmad Mageed


Ahmad's answer is good. There is also an empty constructor, even though strangely, there's no trace of it on MSDN:

Dim x As New Nullable(Of DateTime)
Debug.Assert(x.HasValue = False)

As expected, HasValue is false. If you have a Nullable(T) with a value, and want to remove that value, you'd just set it to Nothing, as if it was a reference type:

x = New Date(2011, 1, 1)
x = Nothing
Debug.Assert(x.HasValue = False)
like image 43
Meta-Knight Avatar answered Feb 09 '26 07:02

Meta-Knight