BRO1106: Use string.Empty for empty strings¶
"" should be written as string.Empty. 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)
Interpolated ($"") and UTF-8 (""u8) literals are different kinds of literal and aren't reported either.
Configuration¶
[*.cs]
# string_empty (default): string.Empty, like StyleCop
# 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 @.
Compared with StyleCop¶
Same results as StyleCop. The literal style is the opposite of StyleCop's rule (Roslynator's RCS1078 has the same
choice).