Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Types in VB.NET?

Tags:

vb.net

People also ask

What do you mean by nullable type?

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.

What is nullable value type?

A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value. The Nullable types are instances of System.

How do I set an integer to null in VB net?

Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer.

Why do we need nullable types?

We are using nullable types when we need to represent an undefined value of an underlying type. While Boolean values can have either true or false values, a null in this case means false as there is no undefined value. When you have a database interaction, a variable value can be either undefined or missing.


VB.Net does have nullable types, they can be declared in the following two different ways.

Dim iNullable As Integer?

or

Dim iNullable As Nullable(Of Integer)

Nullable types can be used in VB.NET same as in C#.

You can't assign Null, Nothing or DBNull to a bare Integer in VB but you can use a Nullable(Of Integer) instead:

Dim x As Integer? = Nothing

Alternatively, it sometimes (but rarely) makes sense to box the integer value in an Object (which can be Nothing).


Integers (System.Int32 etc) in .NET are not directly nullable; however, there is Nullable-of-T that allows you to make any value-type nullable-ish. Note that you may have to check the database against DBNull rather than null/Nothing.

So yes, you can do something very similar.


In a number of cases Nothing will get converted to the default value. To use Nothing the same way you would use null you need to cast it to the correct nullable type.

Dim str As String
Dim int As Nullable(Of Integer) ' or use As Integer?
Dim reader As SqlDataReader
Dim colA As Integer = reader.GetOrdinal("colA")
Dim colB As Integer = reader.GetOrdinal("colB")
str = If(reader.IsDBNull(colA), DirectCast(Nothing, String), reader.GetString(colA))
int = If(reader.IsDBNull(colB), DirectCast(Nothing, Nullable(Of Integer)), reader.GetInt32(colB))