BRO1106: Use string.Empty for empty strings¶
"" should be written as string.Empty, and so should the other ways of writing an empty string: @"", an
interpolated string without content ($"", $@"") and a raw string literal whose value is empty (three quotes, an
empty line, three quotes). Replaces StyleCop SA1122.
Example¶
Before¶
public class Person
{
public string Name { get; set; } = "";
public bool HasName() => Name != "";
}
After¶
public class Person
{
public string Name { get; set; } = string.Empty;
public bool HasName() => Name != string.Empty;
}
Why¶
string.Empty states the intent, while "" can look like a string that is missing its text, or one where a space was
lost. One way of writing it also makes empty strings easy to search for.
Not reported¶
string.Empty is not a compile-time constant, so wherever C# requires a constant the literal stays:
constfields and locals, including a""inside a longer constant expression (const string X = "" + "a")- attribute arguments:
[Obsolete("")] - parameter default values:
void M(string s = "") case ""labels and patterns:s is "","" => ...in a switch expression (the arm's result,_ => "", is replaced)
The same holds for the other forms: const string X = $"" and [Obsolete($"")] stay.
An empty interpolated string that isn't used as a string stays as well: as a FormattableString, an IFormattable or
an interpolated string handler (FormattableString text = $""), string.Empty wouldn't compile or would mean
something else.
A UTF-8 literal (""u8) is a different kind of literal and isn't reported either.
Neither form is reported in an expression tree (an Expression<...> lambda or a query over IQueryable): "" is a
constant there and string.Empty a field access, so the fix would change the tree the program sees at run time. Nor in
a delegate lambda written the same way as an expression-tree lambda of the same member: code that decompiles the delegate
compares the pair.
Configuration¶
[*.cs]
# string_empty (default): string.Empty
# literal: ""
stylebro_empty_string_style = string_empty
With literal, the rule reports the other way around: string.Empty (also written String.Empty or
System.String.Empty) becomes "", everywhere, since a literal is valid in every context.
// Before (stylebro_empty_string_style = literal)
public string Name { get; set; } = string.Empty;
public bool HasName() => Name != String.Empty;
// After
public string Name { get; set; } = "";
public bool HasName() => Name != "";
Not reported in the literal style: a member named Empty on another type, nameof(string.Empty) (nameof("") doesn't
compile), and an access with a comment inside it (string /* x */ .Empty). A verbatim @"" is left to
BRO1138, which removes the @.