Search code examples
c#stringremoving-whitespaceisnullwriter

How to understand "!string.IsNullOrWhiteSpace(s)" syntax?


Well, I know in fact that "!" means NOT, and I quite understand the "IsNullOrWhiteSpace" function destination. But once upon, when I surfed through the Internet in terms of finding how to delete whitespaces, I've faced that kind of syntax:

if (!string.IsNullOrWhiteSpace(s))
{
    writer.WriteLine(s);
}

How should I understand such a syntax? Exclamation mark before the DATATYPE(!!!), then the datatype calls the function with the parameter of my string, later being written to some file. And, by the way, is there a better approach to delete empty lines if my file from where I read text has several (maybe, more or less) whitespaces between the actual strings?


Solution

  • The snippet you posted doesn't delete empty lines, it just skips them from writing. It means that writer.WriteLine(s); part not called for empty lines.

    Exclamation mark before the DATATYPE(!!!)

    It's not before the datatype, it's before the call for a static method IsNullOrWhiteSpace of the System.String type. You could research here about it. The result of this method is boolean. So you're applying a negation operator (!) to the boolean result. When the result equals true i.e. the string passed to the IsNullOrWhiteSpace method in the s parameter is null or white space the negation operator is making it false and vice versa. After that the if statement takes the result of ! operator work (true or false) and decides what to do next.

    And, by the way, is there a better approach to delete empty lines if my file from where I read text has several (maybe, more or less) whitespaces between the actual strings?

    So you're reading from the file and writing to another or the same file. Your approach will work, but keep in mind, that s must be a single line from your initial file, not a word or a symbol.