Skip to content

Latest commit

 

History

History
65 lines (46 loc) · 1.82 KB

ECS0006.md

File metadata and controls

65 lines (46 loc) · 1.82 KB

ECS0006: Avoid stringly-typed APIs

This rule is described in detail in Effective C#: 50 Specific Ways to Improve your C#

Cause

Using string literals to represent member names or parameter names in APIs.

Rule description

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.

How to fix violations

Replace the string literal with the nameof operator to reference the member or parameter name.

When to suppress warnings

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.

Example of a violation

Description

Using a string literal to reference a member name.

Code

public class MyClass
{
    public static void ExceptionMessage(object thisCantBeNull)
    {
        if (thisCantBeNull == null)
        {
            throw new ArgumentNullException(
                "thisCantBeNull",
                "We told you this cant be null");
        }
    }
}

Example of how to fix

Description

Replacing the string literal with the nameof operator.

Code

public class MyClass
{
    public static void ExceptionMessage(object thisCantBeNull)
    {
        if (thisCantBeNull == null)
        {
            throw new ArgumentNullException(
                nameof(thisCantBeNull),
                "We told you this cant be null");
        }
    }
}