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.
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.
Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With