Make Simple Data Types Nullable
With the new support for generics that's found in the .NET Framework, a number of new features become possible. One of these features—generic strongly typed collections—was demonstrated in the previous lab, "Build Typesafe Generic Classes." Now you'll see another way that generics can solve common problems, this time by using the new nullable data types.
Note
Do you need to represent data that may or may not be present? VB . NET's new nullable types fill the gap.
How do I do that?
A null value (identified in Visual Basic by the keyword Nothing), is a special flag that indicates
no data is present. Most developers are familiar with null object
references, which indicate that the object has been defined but not
created. For example, in the following code, the FileStream contains a null reference because
it hasn't been instantiated with the New keyword:
Dim fs As FileStream
If fs Is Nothing
' This is always true because the FileStream hasn't
' been created yet.
Console.WriteLine("Object contains a null reference.")
End IfCore data types like integers and strings
can't contain null values. Numeric variables are
automatically initialized to 0.
Boolean variables are False. String
variables are set to an empty string (''") automatically. In fact,
even if you explicitly set a simple data type variable to Nothing in your code, it will automatically
revert to the empty value (0,
False, or ""), as the following
code demonstrates:
Dim j As Integer = Nothing If j ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access