Code inspection: Cast expression can be replaced with lambda return 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.
If the upcast happens inside a lambda expression body, the return annotation of the lambda expression can be used to get rid of the cast expression:
interface IBase;
interface IDerived : IBase;
class Derived : IDerived;
class Sample
{
public Sample()
{
var derivedInstance = new Derived();
IEnumerable<IDerived> derivedItems =
[derivedInstance, derivedInstance];
var baseItems = derivedItems.Select(x => (IBase)x).ToList();
}
}
interface IBase;
interface IDerived : IBase;
class Derived : IDerived;
class Sample
{
public Sample()
{
var derivedInstance = new Derived();
IEnumerable<IDerived> derivedItems =
[derivedInstance, derivedInstance];
var baseItems = derivedItems.Select(IBase (x) => x).ToList();
}
}
Last modified: 06 August 2024