This rule is described in detail in Effective C#: 50 Specific Ways to Improve your C#
Using string literals to represent member names or parameter names in APIs.
This rule identifies instances where string literals are used to refer to member names or parameter names. Using string literals in such contexts is prone to errors, especially during refactoring, as the string literals do not update automatically. The nameof
operator should be used instead to ensure type safety and to facilitate easier refactoring.
Replace the string literal with the nameof
operator to reference the member or parameter name.
Suppress warnings only if you have a valid reason for using string literals that cannot be replaced with the nameof
operator. For example, if the string literal represents a dynamic value that cannot be determined at compile time.
Using a string literal to reference a member name.
public class MyClass
{
public static void ExceptionMessage(object thisCantBeNull)
{
if (thisCantBeNull == null)
{
throw new ArgumentNullException(
"thisCantBeNull",
"We told you this cant be null");
}
}
}
Replacing the string literal with the nameof
operator.
public class MyClass
{
public static void ExceptionMessage(object thisCantBeNull)
{
if (thisCantBeNull == null)
{
throw new ArgumentNullException(
nameof(thisCantBeNull),
"We told you this cant be null");
}
}
}