JetBrains Rider 2023.1 Help

Code Inspection: Type check and casts can be replaced with try cast

JetBrains Rider suggests that you replace the following sample code

if (myObject is SomeType) { var someType = (SomeType)myObject; someType.DoSomething(); }

with

var o = myObject as SomeType; if (o != null) { var someType = o; someType.DoSomething(); }

Let's see why.

First, there are two casts in the initial sample: myObject is SomeType and (SomeType)myObject (isinst and castclass in IL), while the fixed code has only one cast myObject as SomeType (a single isinst in IL).

Second, the initial sample is not thread-safe: if another thread changes myObject after is and before the cast, the cast can throw an InvalidCastException.

Note that JetBrains Rider will not suggest this fix for value types because the as operator can be used only with reference types or instances of the System.Nullable struct. Using the initial pattern for value types is not a bad idea for the reasons explained in this StackOverflow question.

Last modified: 08 March 2021