Upraviť

Zdieľať cez


Add explicit cast (IDE0221)

Property Value
Rule ID IDE0221
Title Add explicit cast
Category Style
Subcategory Language rules (expression-level preferences)
Applicable languages C#
Options dotnet_style_prefer_non_hidden_explicit_cast_in_source

Overview

This rule flags explicit casts in source code where the compiler inserts an additional hidden explicit cast. Both the visible and hidden casts can fail at runtime for different reasons. When this rule flags such code, it recommends adding the intermediate cast explicitly in source to make the code's intent clear.

For example, if you write (Derived)x where x is of a type that requires two explicit conversions—first to a base type and then to the derived type—only one cast is visible in source. The compiler inserts the intermediate cast without any indication in the source. This rule suggests writing both casts explicitly: (Derived)(Base)x.

Options

Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.

dotnet_style_prefer_non_hidden_explicit_cast_in_source

Property Value Description
Option name dotnet_style_prefer_non_hidden_explicit_cast_in_source
Option values true Prefer to make all intermediate explicit casts visible in source code.
false Don't prefer to make all intermediate explicit casts visible in source code.
Default option value true

Example

class Base { }
class Derived : Base { }

class Castable
{
    public static explicit operator Base(Castable c) => new Base();
}

class C
{
    void M()
    {
        // Code with violation: the compiler inserts a hidden (Base) cast.
        var v = (Derived)new Castable();

        // Fixed code: both casts are explicit in source.
        var v2 = (Derived)(Base)new Castable();
    }
}

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 IDE0221
// The code that's violating the rule is on this line.
#pragma warning restore IDE0221

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

[*.cs]
dotnet_diagnostic.IDE0221.severity = none

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

[*.cs]
dotnet_analyzer_diagnostic.category-Style.severity = none

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

See also