Why Is string.IsNullOrWhiteSpace(“\0”) False in .NET?

.netc#-4.0string

I faced a problem where invisible character \0 which is pretty like a 'white space' not considered as white space by the string.IsNullOrWhiteSpace method. I wonder why this implemented in .NET in so manner and is there any alternative to string.IsNullOrWhiteSpace which can properly handle null-terminate character?
Thanks in advance.

Best Answer

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.

Related Question