All rules
IDE0221Language rules (expression-level preferences)

Add explicit cast

Add explicit cast

Microsoft docs

Description

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.

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();
    }
}

Configurable options

Vote for the value each option should take in the generated .editorconfig.

dotnet_style_prefer_non_hidden_explicit_cast_in_source
default: true
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0