ReSharper 2017.1 Help

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

ReSharper suggests to 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 only used with reference types or instances of the System.Nullable struct. And after all, using the initial pattern for value types is not a bad idea for the reasons explained in this StackOverflow question.

See Also

Last modified: 4 July 2017