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:
- Why is this? Since the
Nullable(Of T)structure was created specifically for this type of situation, why would the default behavior beHasValue=True? - What’s the best way to initialize a
Nullable(Of T)to actually benull?
Thanks!
If you’re supplying a value to the
Nullableconstructor then it will have the given value, which would result in the scenario you’re describing whereHasValueis true.To declare a nullable with a
HasValueoffalseyou can take either of these approaches:However, if you’re using the constructor and supplying a value, the nullable struct won’t have a null value, and it’s
HasValuewould betrue: