.NET Tips and Tricks

Blog archive

Is There Anything in that String?

String variables look like value types, those variables holding integers and dates. But, under the hood, strings are more like reference types, those variables that point to objects. This means that you can set a string to Nothing/null, something you can't do with integers (though you can with a variation on some value types). While a string variable set to Nothing/null is obviously a string with 'nothing there,' you probably also consider a string set to String.Empty or "" (a zero-length string, or ZLS) as 'nothing there.' In some conditions, you may even consider a bunch of blanks ("     ") as 'nothing there.'

.NET provides a method for checking these conditions, and .NET 4 adds a new version that does a little more. The earlier method is the static/shared method IsNullOrEmpty, which returns True if a string is set to any of String.Empty, null/Nothing or a ZLS, but returns false for a string of blanks:

Dim res As Boolean
Dim tester As String
tester = Nothing
res = String.IsNullOrEmpty(tester) 'res is True
tester = String.Empty
res = String.IsNullOrEmpty(tester) 'res is True
tester = ""
res = String.IsNullOrEmpty(tester) 'res is True
tester = "    "
res = String.IsNullOrEmpty(tester) 'res is False

.NET 4 adds a new method named IsNullOrWhitespace which does the same thing as IsNullOrEmpty, but also returns True for a string of blanks or anything else that .NET classifies as whitespace. Whitespace is anything that returns True from char.IsWhiteSpace and includes, for example, tabs and carriage returns/linefeeds:

tester = vbTab
res = String.IsNullOrWhiteSpace(tester) 'res is True
The key issue in choosing between the two is whether you consider a string of blanks/tabs/carriage returns/linefeeds as 'nothing there' (use IsNullOrWhitespace) or as 'something there' (use IsNullOrEmpty).

Posted by Peter Vogel on 09/11/2013


comments powered by Disqus

Featured

  • See Prompts Microsoft Engineers Use for Bleeding-Edge Multimodal RAG AI Research

    Vision-centric queries show how front-line experts are prompting LLMs these days.

  • AI Explains Expressions in Update to Java on VS Code

    "The Spring Tools now show code lenses above these expressions that allow you to quickly let GitHub Copilot explain those statements for you."

  • Microsoft Eases Integration with Semantic Kernel AI SDK

    The basic idea is to provide unified API abstractions, especially for idiomatic C# code, to help platform developers and others work with any provider with standard implementations for caching, telemetry, tool calling and other common tasks.

  • Final .NET 9 Preview Ships with Go-Live License

    Visual Studio developers can now download the SDK for .NET 9 Release Candidate 2 with a go-live license, meaning devs get Microsoft support for production applications even before the framework reaches general availability next month.

Subscribe on YouTube