Code inspection: Cast expression can be replaced with explicit variable type
Category: Common Practices and Code Improvements
ID: CanReplaceCastWithVariableType
EditorConfig: resharper_can_replace_cast_with_variable_type_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
C-style cast expression in C# can be both a static upcast and a dynamic downcast, both having the same syntax. Without keeping the type hierarchies in mind, there is no way to tell if the cast is a safe upcast or a runtime downcast. Moreover, a static upcast can be accidentally turned into a dynamic downcast during a refactoring. To avoid these problems and make code less fragile, this inspection suggests using an explicit type instead of the cast where possible.
Suboptimal code
interface IBase;interface IDerived : IBase;class Derived : IDerived;class Sample{ public Sample() { var derivedInstance = new Derived();// upcast: var baseReference = (IBase) derivedInstance;// downcast: var derivedReference = (IDerived) baseReference; }}
After the quick-fix
interface IBase;interface IDerived : IBase;class Derived : IDerived;class Sample{ public Sample() { var derivedInstance = new Derived();// implicit upcast: IBase baseReference = derivedInstance;// downcast: var derivedReference = (IDerived) baseReference; }}
Such initialization of baseReference
will not compile if the derivedInstance
variable changes its type so that it is no longer compatible with IBase
.