I noticed that Resharper suggests that I turn this:
if (myObj.myProp is MyType)
{
...
}
into this:
var myObjRef = myObj.myProp as MyType;
if (myObjRef != null)
{
...
}
Why would it suggest this change? I’m used to Resharper suggesting optimization changes and code reduction changes, but this feels like it wants to take my single statement and turn it into a two-liner.
According to MSDN:
An is expression evaluates to true if both of the following conditions
are met:expression is not null. expression can be cast to type. That is, a
cast expression of the form(type)(expression)will complete without
throwing an exception.
Am I misreading that, or doesn’t is do the exact same checks, just in a single line without the need to explicitly create another local variable for the null check?
Because there’s only one cast. Compare this:
to this:
C# 7.0 supports a more compact syntax using pattern matching: