JetBrains Rider 2024.3 Help

Code inspection: Cast expression can be replaced with explicit type arguments

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.

In the generic context, you can use an explicit type argument instead of a cast in the argument:

interface IBase; class Derived : IBase; class Sample { public Sample() { var derivedInstance = new Derived(); Task<IBase> task = Task.FromResult((IBase)derivedInstance); } }
interface IBase; class Derived : IBase; class Sample { public Sample() { var derivedInstance = new Derived(); Task<IBase> task = Task.FromResult<IBase>(derivedInstance); } }
Last modified: 26 July 2024