JetBrains Rider
 
2024.3
Get JetBrains Rider

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

Last modified: 25 July 2024

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.

Such initialization of baseReference will not compile if the derivedInstance variable changes its type so that it is no longer compatible with IBase.