Why string.IsNullOrWhiteSpace("\0") is false

U+0000 isn't whitespace, basically. char.IsWhitespace('\0') returns false, it's not listed as whitespace...

The null part of IsNullOrWhitespace refers to the string reference itself - not the contents, if that's what you were thinking of.

Note that strings in .NET aren't logically "null-terminated" within managed code, although in practice at the CLR level they are, for interop purposes. (The string knows its own length, but in order to make it easier to work with native code which does expect a null terminator, the CLR ensures that there's always a U+0000 after the content of the string.) If you end up with a string containing \0 you should probably fix whatever produced it to start with.


You could replace all \0 characters with the space character, and then check for whitespace.

string.IsNullOrWhiteSpace("\0".Replace('\0', ' ');

For fun historical reasons (they are surely fun, but I wasn't able to find them), null has two meanings... The null pointer/reference (called NULL in C), and the NUL (or NULL) \0 character.

String.IsNullOrWhiteSpace does:

Indicates whether a specified string is null, empty, or consists only of white-space characters.

with null meaning the "null reference", empty meaning empty and white-space meaning

White-space characters are defined by the Unicode standard. The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char.IsWhiteSpace method as a white-space character.

The list of characters that Char.IsWhiteSpace considers a space is present in the page of Char.IsWhiteSpace.