Nullable Types in .NET Framework

Within the .NET Framework data types such as Boolean can either be true or false. Right?  Well, with the release of 2.0 Framework it has been possible to create nullable data types.  A nullable type can represent all the values of the underlying type plus empty (or undefined).  In the case of our Boolean it would be True/False and Nothing.

It is only possible to create a nullable types Nullable(Of T) for value types since the default value for reference types is already nothing.  The following types are valid as nullable: Boolean, Byte, Int16, Int32, Int64, Single, Double, Decimal, DateTime.  The following examples show examples on how to create a nullable variable type:

Dim success as New Nullable(Of Boolean)()

Dim customerId as New Nullable(Of Integer)()

With the release of .NET 3.5 it is also possible to use the short form versions:

Dim success as Boolean?
Dim customerId as Integer?

In C#

bool? success;
int? customerId;

To check of a nullable type as a value it is possible to use the HasValue  or Value properties.  Use the System.Nullable.GetValueOrDefault property return either the assigned value, or the default value for the underlying type.  

If customerId.HasValue Then
  ‘do something
End If

If assigning a nullable type to a non-nullable type you must cast operator is necessary.  For example:

int newCustomerId = (int)customerId;  // in C#

Nullable types can be useful when dealing with NULL values from a database query however they are not the same.  That is to say that DBNULL value is not the same as Nothing.  When returning data from the database the following code will be necessary:

int? customerId = null;

if (!DBNULL.Value.Equals(reader[“CustomerId”])){    // this code converts the DBNULL to a c# null
  customerId = (int)reader[“CustomerId”];
}


Author

Admin

comments powered by Disqus

Categories

Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F