Nullable data types in Visual Basic 9.0

I know we are in Visual Studio 2010 and VB 10.0 version of the language-compiler.Most people I know (in my country anyway) work still with VS 2008 and .Net 3.5 SP1 version.

In this post I would like to talk about language improvements in visual basic 9.0 and more specifically about nullable data types.

The largest improvement in Visual basic 9.0 is LINQ. So all these enhancements that were made in the VB 9.0 language (the same goes for c# 3.0 enhancements) had LINQ in mind and how LINQ will be able to work.

Nullable data types enable us to create data types e.g integers and set them-initialise them to the value nothing, null.

In our database design we often have tables where fields are allowed to have NULL.

Prior to Visual Basic 9.0 one should turn the null value from the database into a zero value in the application.

Nullable data types help us to avoid this mismatch in LINQ to SQL.

The problem is that representing a null (nothing) value with zero is wrong, because null means something that is uknown and by setting it to zero, well you set it to something that is known.

In order to demonstrate this enhancement-new feature I will create a simple Asp.Net application using VB and Visual Studio 2008.

1) Launch Visual Studio 2008

2) Create a new project (ASP.NET web application)  and choose VB as the project’s language

3) Name it “nullabledata” or any other name you want

4) Add a button in the default.aspx page

5) Double click in the button

6) In the event handling routine that is created just type the following

Dim mynum As Integer? = 4
Dim myothernum As Integer? = Nothing
Dim myres As Integer = 0

myres = mynum + myothernum


by adding the ? operator after the data type, we indicate that the variable mynum can be set to nothing.

We declare another variable in this statement

Dim myothernum As Integer? = Nothing

This can only be valid in VB 9.0

Try and run your application by hitting F5.

Click on the button. You will receive an error – exception.

the problem is that the variable with the name myres is not nullable.

When you add 4 with an uknown value you do not get 4. You get an uknown value.

The solution to this problem is to create another variable that is nullable this time.

Dim myfinalres As Integer?

comment out these lines

myres = mynum + myothernum


and type these lines

myfinalres = mynum + myothernum


Now if you run the application again and press the button you will receive the value of Nothing.

No Comments