Code Inspection: Type check and casts can be replaced with try cast
ReSharper suggests that you replace the following sample code
Let's see why.
First, there are two casts in the initial sample:
myObject is SomeType 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
is and before the cast, the cast can throw an
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.