Nullable. Consider an Integer in VB.NET. It cannot be null—it can only have a numeric value. But we can wrap the Integer inside a nullable Structure, which can logically be Nothing.
With properties and functions, we can test a Nullable. We specify a nullable type by adding a question mark after the type name. For the value, we can access Value.
An example. Here we see a nullable Integer named "element." We use the Integer in various ways. We use the Nothing value to indicate "null" in the VB.NET language.
Note The HasValue property returns true or false. It indicates whether an underlying value is contained in the nullable.
Note 2 The GetValueOrDefault function safely returns the underlying value. If the nullable has no value, it returns the value type's default.
Finally The Value property will throw an exception if the nullable has no value. Prefer GetValueOrDefault to avoid exceptions.
Module Module1
Sub Main()
' A nullable can be Nothing.
Dim element As Integer? = Nothing
Console.WriteLine("HASVALUE: {0}", element.HasValue)
Console.WriteLine("GETVALUEORDEFAULT: {0}", element.GetValueOrDefault())
' Use an Integer value for the nullable Integer.
element = 100
Console.WriteLine("VALUE: {0}", element.Value)
Console.WriteLine("GETVALUEORDEFAULT: {0}", element.GetValueOrDefault())
End Sub
End ModuleHASVALUE: False
GETVALUEORDEFAULT: 0
VALUE: 100
GETVALUEORDEFAULT: 100
Notes, null. In VB.NET the keyword "Nothing" is used to indicate null. This makes types like nullable somewhat confusing, because they are based on C# terms.
A summary. What is a null Integer or other null value type? A null thing can be used to indicate an uninitialized value—we can have uninitialized, or an actual number set.
In this way, nullable types can help eliminate ambiguous parts of programs. We do not need to use -1 as a special value meaning "not set." We can use null.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 19, 2023 (edit).