Code inspection: Cast expression can be replaced with explicit variable type
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.
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;
}
}
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
.
Last modified: 25 July 2024