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

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

Last modified: 21 March 2024

JetBrains Rider suggests that you replace the following sample code

with

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.