Code inspection: Safe cast expression always succeeds
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.