ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Safe cast expression always succeeds

Last modified: 08 April 2024

To safely cast a reference variable from a derived type to a base type or vice versa, you can use as operator. Safely means that the code will not throw an exception, but rather a variable to which you assign a value will be assigned null if the cast cannot be performed.

If the types are compatible, a safe cast using as would always succeed, so in this case the explicit cast would be enough as redundant casts might decrease performance.

A cast from base to derived type might be redundant if the variable of a base type was already checked for compatibility with the derived type. In the example below the assignment of string str is only possible when obj is of the type string and it is not null. So we can either use a direct cast or rewrite this code to separate the cast from null-checking.

When a safe cast is used for a conversion from a base to derived type, then it is not necessary at all (the compiler will implicitly perform the cast anyway) and can be safely removed.