String.IsNullOrEmpty does not detect NULL \ 0 sequence in C #
I tried the following if statement but if it couldn't find NULL
void Main()
{
string str = "\0".Trim();
if (string.IsNullOrEmpty(str))
{
"Empty".Dump();
}
else
{
"Non-Empty".Dump();
}
}
Link to LinqPad snapshot
I got output
Non-Empty
I don't know how it goes. Please help me.
Your string contains one character \0
.
This character is not printed, so you don't see it in the clock, but if you add it str.Length
to the clock, you will see "1".
So, is your string null? Definitely not. Is it empty? No, it contains symbols.
Hence, string.IsNullOrEmpty
logically leads to false
and outputs "Non-Empty".
If for some reason you get strings containing characters \0
and want to treat them as an empty string, you can simply trim \0
:
string str = "\0".Trim(new[] { '\0', ' ', '\t' });
if (string.IsNullOrEmpty(str))
{
"Empty".Dump();
}
else
{
"Non-Empty".Dump();
}
This will display "Empty".
As suggested by Patrick Hoffman, it is better to use string.IsNullOrWhiteSpace
as it is more suitable for this case and can handle a wider range of white spaces, invisible BOM characters, etc.
source to share