JetBrains Rider 2017.2 Help

Code Inspection: Safe cast expression always succeeds, consider direct cast instead

JetBrains Rider issues this suggestion in two situations: when you convert compatible types from derived to base and also when you convert a base type to a derived one.

To safely cast a reference variable from a derived type to a base type, the as operator is used. The safety 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.

In the example, type compatibility is checked first (by using the is operator), and the cast is performed only if the types are compatible. The presence of checking with is makes using as redundant. Redundant casts might decrease performance. JetBrains Rider detects a safe cast from a compatible derived type and replaces this cast with a direct cast:

Suboptimal codeAfter the quick-fix
class SafeCastDemo { public class Animal { } private class Cat : Animal { } public Animal GetCat(Animal a) { Cat c = new Cat(); if (a is Cat) { c = a as Cat; } return c; } }
class SafeCastDemo { public class Animal { } private class Cat : Animal { } public Animal GetCat(Animal a) { Cat c = new Cat(); if (a is Cat) { c = (Cat) a; } return c; } }

Another situation when a safe cast always succeeds is a conversion from a base to derived type, when no explicit cast is necessary at all (the compiler implicitly performs it). So the quick-fix that removes a safe cast appears also when a conversion from a base to derived type takes place. Because no cast is needed for such a conversion, the code below also invokes another quick-fix that removes the explicit cast altogether. The example shows the result after both quick-fixes have been applied (the safe cast and then the explicit cast have been removed).

Suboptimal codeAfter the quick-fix
class SafeCastDemo { class Animal { } class Cat : Animal { } class Program { static void Main() { Cat с = new Cat(); Animal a = c as Animal; // ... } } }
class SafeCastDemo { class Animal { } class Cat : Animal { } class Program { static void Main() { Cat с = new Cat(); Animal a = c; // ... } } }
Last modified: 17 November 2017

See Also