In C#, how do `string.IsNullOrEmpty` and `string.IsNullOrWhiteSpace` differ, and does writing `string.Empty` instead of `""` change anything?
answer
- zero length versus blank
- char.IsWhiteSpace decides
- NotNullWhen(false) helps flow analysis
- constant versus static readonly
basics
~20 sIsNullOrEmpty is true only for null or a zero-length string; IsNullOrWhiteSpace is also true when every character is white space, such as spaces, tabs or line breaks. string.Empty and "" are one instance; only "" is a constant.
solid answer
~40 s`string.IsNullOrEmpty(s)` is exactly `s == null || s.Length == 0`. `string.IsNullOrWhiteSpace(s)` returns true for null and otherwise checks every character with `char.IsWhiteSpace`, so `" "`, `"\t\r\n"` and a no-break space count as blank, while a zero-width space (U+200B) does not, because Unicode classes it as a format character. Use `IsNullOrWhiteSpace` to reject blank user input such as a product name, and `IsNullOrEmpty` when white space is meaningful content. Both are annotated `[NotNullWhen(false)]`, so after a false result the compiler treats `s` as non-null. `string.Empty` and `""` are the same object at run time and neither allocates; the difference is that `""` is a compile-time constant, so only it works in a `const`, a default parameter value or a `case` label, while `string.Empty` is a `static readonly` field.
code
csharp · 14 lines(string Label, string? Value)[] inputs =
[
("null", null), ("empty", ""), ("spaces", " "), ("tab+newline", "\t\r\n"),
("no-break space", " "), ("zero-width space", ""), ("product name", " Desk Lamp "),
];
foreach (var (label, value) in inputs)
Console.WriteLine($"{label,-17} IsNullOrEmpty={string.IsNullOrEmpty(value),-5} IsNullOrWhiteSpace={string.IsNullOrWhiteSpace(value)}");
Console.WriteLine(ReferenceEquals(string.Empty, "")); // True: one shared instance
string? missing = null;
Console.WriteLine(missing == ""); // False, no exception
Console.WriteLine(string.IsNullOrWhiteSpace(missing) ? "rejected" : missing.Length.ToString());go deeper
Know the difference: IsNullOrEmpty means null or no characters, IsNullOrWhiteSpace also treats spaces, tabs and line breaks as blank. Use the latter for required text fields.
Explain that char.IsWhiteSpace decides, why a zero-width space is not white space, how NotNullWhen(false) informs nullable flow analysis, and where only a constant "" compiles.
Choose checks deliberately per field: blank-rejecting validation for names, IsNullOrEmpty where spaces are data, and no allocation from Trim just to test emptiness.
Settle string.Empty versus "" as a style rule enforced by tooling rather than review debate, and define what counts as blank input consistently across services.
## The two checks Both are static methods on `System.String`, and the runtime source is short enough to quote in words: - **`IsNullOrEmpty(string? value)`** returns `value == null || value.Length == 0`. - **`IsNullOrWhiteSpace(string? value)`** returns true for null, then loops over the characters and returns false at the first one for which `char.IsWhiteSpace` is false; an empty string, or one made only of white space, returns true. Run on .NET 10, they disagree only on non-empty strings made entirely of white space: | Input | `IsNullOrEmpty` | `IsNullOrWhiteSpace` | |---|---|---| | `null` | true | true | | `""` | true | true | | `" "` | false | true | | `"\t\r\n"` | false | true | | `"\u00A0"` (no-break space) | false | true | | `"\u200B"` (zero-width space) | false | false | | `" Desk Lamp "` | false | false | ## What counts as white space `char.IsWhiteSpace` follows Unicode: spaces, tabs, line feeds, carriage returns, the no-break space and the other space separators all qualify. The zero-width space U+200B is classed as a **format** character, not white space, so a name consisting only of zero-width spaces looks blank on screen yet passes `IsNullOrWhiteSpace` as non-blank. If such input matters to you, that is a Unicode-handling decision covered with characters and text elements; the checks themselves are behaving as specified. `string.Trim()` uses the same `char.IsWhiteSpace` test, so for a non-null string `IsNullOrWhiteSpace(s)` agrees with `s.Trim().Length == 0`. The method is still the better choice: it handles null, and it does not allocate a trimmed copy just to measure it. ## Null safety and flow analysis - **Calling members on null throws.** `s.Length == 0`, `s.Trim() == ""` and `s.Equals("")` all throw `NullReferenceException` when `s` is null. The static methods and `s == ""` do not; `==` with a null operand simply returns false. - **The compiler knows the result.** Both methods mark their parameter `[NotNullWhen(false)]`, so in a nullable-enabled project `if (string.IsNullOrWhiteSpace(name)) return;` lets the following `name.Length` compile without a CS8602 warning. - **Analyzer advice.** Rule CA1820 flags comparing with `Equals("")` and recommends `Length == 0` or `string.IsNullOrEmpty`; it is not enabled by default in .NET 10. ## string.Empty versus "" On .NET 10, `ReferenceEquals(string.Empty, "")` prints `True`: the field and the literal are the same object, and using either allocates nothing. Performance is not a reason to prefer one. The real difference is in the language: 1. `""` is a **constant**; `string.Empty` is declared `public static readonly string Empty;`, which is not. 2. `const string None = string.Empty;` fails with CS0133, "The expression being assigned to 'None' must be constant". 3. `void Find(string sku = string.Empty)` fails with CS1736, because a default parameter value must be a compile-time constant. 4. `case string.Empty:` in a `switch` fails with CS9135, "A constant value of type 'string' is expected". 5. Attribute arguments need constants too, so only `""` fits there. Outside those places the choice is style; many teams pick one and let an editor rule enforce it. ## Choosing a check - **Required free-text fields** such as a product name or a search term: `IsNullOrWhiteSpace`, then `Trim()` the value you store. - **Values where spaces are data**, such as a fixed-width record field or a password: `IsNullOrEmpty`, so a value of spaces is not mistaken for missing. - **Only null matters**: `is null`, without either method. - **Comparing with empty**: `s.Length == 0` when `s` is known to be non-null; otherwise `string.IsNullOrEmpty(s)`. The interview answer: one checks for no characters, the other for no visible characters as `char.IsWhiteSpace` defines them, both handle null and inform flow analysis, and `string.Empty` versus `""` matters only where a constant is required.
- Why does the compiler stop warning about `name.Length` after `if (string.IsNullOrWhiteSpace(name)) return;`?Both methods mark their parameter `[NotNullWhen(false)]`. The nullable flow analysis reads that attribute: when the call returns false, the argument is known to be non-null, so `name.Length` after the early return produces no CS8602 warning.
- How can a name that looks blank still pass `IsNullOrWhiteSpace` as non-blank?If it contains invisible characters that Unicode does not class as white space, such as the zero-width space U+200B, a format character. `char.IsWhiteSpace` returns false for it, so the string counts as having content. Rejecting such input takes an explicit rule about which characters you allow.
- string.Empty avoids allocating a new string each time "" is written.
- IsNullOrWhiteSpace only looks for the plain space character.
- s.Length == 0 is a safe emptiness check even when s may be null.
- string.Empty works as a default parameter value or a case label.
- s.Trim().Length == 0 is an equally safe way to test a possibly null input.