Search code examples
c#stringnullescapingisnullorempty

String.IsNullOrEmpty is not detecting the Escape sequence NULL \0 in C#


I tried the following if statement but if fails to detect the NULL

void Main()
{
    string str = "\0".Trim();
    if (string.IsNullOrEmpty(str))
    {
        "Empty".Dump();
    }
    else
    {
        "Non-Empty".Dump();
    }
}

Kindly refer the LinqPad snapshot

enter image description here

I got the output

Non-Empty

I don't know how its failing. Kindly assist me.


Solution

  • Your string contains one character \0.
    This character is non-printable, so you don't see it in Watches, but if you add str.Length to watches, you will see "1".

    So, is your string null? Definitely, no. Is it empty? No, it contains characters.
    Hence, string.IsNullOrEmpty logically results into false and it outputs "Non-Empty".

    If for some reason you receive strings containing \0 characters and want to treat it as an empty string, you can just trim \0 as well:

    string str = "\0".Trim(new[] { '\0', ' ', '\t' });
    if (string.IsNullOrEmpty(str))
    {
        "Empty".Dump();
    }
    else
    {
        "Non-Empty".Dump();
    }
    

    This will output "Empty".

    As suggested by Patrick Hofman, it is better to use string.IsNullOrWhiteSpace since it is more suitable for this case and can handle a wider range of white-space, non-visible, BOM characters etc..