Code inspection: Cast expression can be replaced with lambda return type
Category: Common Practices and Code Improvements
ID: CanReplaceCastWithLambdaReturnType
EditorConfig: resharper_can_replace_cast_with_lambda_return_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.
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:
Suboptimal code
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(); }}
After the quick-fix
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(); }}