A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1507 below:

CA1507: Use nameof instead of string (code analysis) - .NET

Property Value Rule ID CA1507 Title Use nameof in place of string Category Maintainability Fix is breaking or non-breaking Non-breaking Enabled by default in .NET 9 As suggestion Cause

A string literal or constant that matches the name of a parameter of the containing method or the name of a property of the containing type is used as an argument to a method.

Rule description

Rule CA1507 flags the use of a string literal as an argument to a method or constructor where a nameof (NameOf in Visual Basic) expression would add maintainability. The rule fires if all of the following conditions are met:

Rule CA1507 improves code maintainability in cases where the parameter may be renamed in the future, but the string literal is mistakenly not renamed. By using nameof, the symbol will be renamed when the parameter is renamed through a refactoring operation. In addition, any spelling mistakes in the name of the parameter are caught by the compiler.

How to fix violations

To fix a violation, replace the string literal with a nameof (NameOf in Visual Basic) expression. For example, the following two code snippets show a violation of the rule and how to fix it:

public Book(string title)
{
    // Violates rule CA1507
    Title = title ?? throw new ArgumentNullException("title", "All books must have a title.");
}
public Book(string title)
{
    // Resolves rule CA1507 violation
    Title = title ?? throw new ArgumentNullException(nameof(title), "All books must have a title.");
}

Tip

A code fix is available for this rule in Visual Studio. To use it, position the cursor on the string literal and press Ctrl+. (period). Choose Use nameof to express symbol names from the list of options that's presented.

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the maintainability of your code.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1507
// The code that's violating the rule is on this line.
#pragma warning restore CA1507

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1507.severity = none

For more information, see How to suppress code analysis warnings.

See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4