mbm29414
mbm29414

Reputation: 11598

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!

Upvotes: 3

Views: 890

Answers (2)

Meta-Knight
Meta-Knight

Reputation: 17855

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)

Upvotes: 2

Ahmad Mageed
Ahmad Mageed

Reputation: 96497

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)

Upvotes: 3

Related Questions