C# Reference ยท Strings and Text
C# String.IsNullOrEmpty() and IsNullOrWhiteSpace() methods
Reference for C# string.IsNullOrEmpty() and IsNullOrWhiteSpace(): check for null, empty and blank strings, nullable flow analysis, and which one to choose.
string.IsNullOrEmpty(s) returns true when s is null or has length zero. string.IsNullOrWhiteSpace(s) is stricter: it also returns true when the string contains only white-space characters such as spaces, tabs and newlines.
They are static methods, so they are safe to call on a null variable. Calling s.Length or s.Trim() on null would throw a NullReferenceException.
if (string.IsNullOrWhiteSpace(input)) { Console.WriteLine("Please type something."); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value)
| Name | Description |
|---|---|
value |
The string to test; may be null. |
Returns: true if the string is null or empty (IsNullOrEmpty), or null, empty or only white space (IsNullOrWhiteSpace).
Errors / undefined behavior: none; neither method throws.
Usage notes
- Nullable flow analysis. The
[NotNullWhen(false)]attribute tells the compiler that after afalseresult the argument is notnull, which removes nullable warnings in the code that follows (see theGreetexample). - Pick the right one for user input. A form field filled with spaces is usually "missing", so
IsNullOrWhiteSpaceis the better default for text typed by people. UseIsNullOrEmptywhen spaces are meaningful, such as a separator or password. - White space follows
char.IsWhiteSpace, so it includes Unicode spaces such as the no-break space, not just the ASCII space. - Cost.
IsNullOrEmptyis a null check and a length check.IsNullOrWhiteSpacescans until it finds a non-space character, which is fast and allocates nothing, unlikes.Trim() == "". - No
IsNullOrEmptyinstance method. You cannot writes.IsNullOrEmpty(); the methods are static (or write your own extension). - Collections. Strings are not the only things that can be empty. For lists use
Count == 0orAny(), orlist is { Count: > 0 }. - Empty versus null often carry different meaning in databases and JSON. Decide on one convention per field and convert at the boundary.
- Pattern matching (
s is null or "") is equivalent toIsNullOrEmpty, ands is { Length: > 0 }is its negation.