Code Focused

Experiencing Nothingness in C# and Visual Basic

Nothing and null are one and the same, except in the language of programming.

When engaging in cross-language development, it's important to worry about nothing – the Visual Basic Nothing keyword, that is, and how it varies from the C# null counterpart. When initializing objects and nullable value types to a "no data" state, the keywords are identical. But null and Nothing have syntax-specific uses that don't travel well between the two languages.

Consider the initialization of standard value types, such as ordinary integer variables. If you want to set an Integer value to its default starting point, and the zero key is broken on your keyboard, you would type the following Visual Basic statement:

' ----- This sets someValue to 0 (zero).
Dim someValue As Integer = Nothing

That statement brings discomfort to C# developers, because you can't assign null directly to a standard integer. Instead, C# uses the default operator to initialize such values:

// ----- This also sets someValue to 0 (zero).
int someValue = default(int);

The role of Nothing as an initializer makes for some interesting coding differences between the two languages. Consider the following Visual Basic statement and its supposed syntactic equivalent in C#:

' ----- The VB verison:
Dim result As String = (5 + Nothing).ToString()

// ----- The C# version:
string result = (5 + null).ToString();

Because Nothing acts as a value type initializer, the parenthesized expression will add five to zero (the default for an integer), eventually storing "5" in the result variable. But the C# code, empowered with that language's single-minded null keyword, behaves differently. Adding null to an int produces null, and the result variable ends up with a zero-length string.

Adding integers and nulls together isn't a typical development scenario, but caution is warranted in the more common practice of letting strings and null values play together. String variables are reference types, and C# treats them as pure reference types, properly differentiating between uninitialized string variables and zero-length strings:

string testValue = null;
if (testValue == "")
  result = "Empty";
else
  result = "Not Empty";

In that C# code, result will be set to "Not Empty," because the testValue null content isn't the same as a zero-length string. For historical reasons, Visual Basic treats null strings and zero-length strings as equivalent. At the end of the following code block, the Visual Basic result variable will contain "Empty," because the testValue comparison with the empty string results in True:

Dim testValue As String = Nothing
If (testValue = "") Then
  result = "Empty"
Else
  result = "Not Empty"
End If

To check for a true non-null, zero-length string in Visual Basic, you must first exclude null instances via the IsNot operator:

If (testValue IsNot Nothing) AndAlso (testValue.Length = 0) Then

It looks like extra work, and it is. But the flexibility of the Visual Basic Nothing keyword does result in simpler code when you want to treat a string as just a string, and not concern yourself with whether it can be null.

About the Author

Tim Patrick has spent more than thirty years as a software architect and developer. His two most recent books on .NET development -- Start-to-Finish Visual C# 2015, and Start-to-Finish Visual Basic 2015 -- are available from http://owanipress.com. He blogs regularly at http://wellreadman.com.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events