ReSharper 2023.3 Help

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

ReSharper suggests that you replace the following sample code

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


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 ReSharper 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: 02 February 2024