Редактиране

Споделяне чрез


Convert typeof to nameof (IDE0082)

Property Value
Rule ID IDE0082
Title Convert typeof to nameof
Category Style
Subcategory Language rules (expression-level preferences)
Applicable languages C# and Visual Basic

Overview

This style rule recommends use of the nameof operator over the typeof operator followed by Name member access. It only fires when the name will be identical in both cases.

Options

This rule has no associated code-style options.

Example

// Code with violations
var n1 = typeof(T).Name;
var n2 = typeof(int).Name;

// Fixed code
var n1 = nameof(T);
var n2 = nameof(Int32);
' Code with violations
Dim n1 = GetType(T).Name
Dim n2 = GetType(Integer).Name

' Fixed code
Dim n1 = NameOf(T)
Dim n2 = NameOf(Int32)

Suppress a warning

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

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

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

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

To disable all of the code-style rules, set the severity for the category Style to none in the configuration file.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

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

See also