Why doesn't the compiler optimize these two throws into one?

I am looking at a function with this template:

if( obj is SpecificClass1 )
{
   ((SpecificClass1)obj).SomeMethod1();
}
else if( obj is SpecificClass2 )
{
   ((SpecificClass2)obj).SomeMethod2();
}
else if( obj is SpecificClass3 )
{
   ((SpecificClass3)obj).SomeMethod3();
}

and get code performance analysis. Warning: CA1800 Do not overuse.

Why double casts (using the "is" operator in an if statement and as brackets enclosed in the body of each if) cannot be optimized by the compiler. I do not understand why this is a performance problem that the compiler cannot solve.

+2
source share
4 answers

To quote Eric Lippert (who worked on the C # team):

: " # X?" . : , , , , . , . , . , , , , , .

0

, , :

if( obj is SpecificClass1 )
{
   ((SpecificClass1)obj).SomeMethod1();
}

to

SpecificClass1 Class1Obj = obj as SpecificClass1;
if (Class1Obj != null)
{
   Class1Obj.SomeMethod1();
}

, , . , , , , .

, :

if( obj is SpecificClass1 )
{
   ((SpecificClass1)obj).SomeMethod1();
   ((SpecificClass1)obj).SomeMethod2();
   ((SpecificClass1)obj).SomeMethod3();
}

, , . , , , , ?

+3

: .

, as , (is () cast):

Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
  Console.WriteLine(b.ToString());
}

, is cast.

+2

The second cast may be ruled out by the optimizing compiler, but this is not required, and the C # memory model may interfere with this optimization in many common cases. If you always use the preferred form with the operator as, you get the benefits of this "optimization" regardless of whether the compiler implements special logic to detect and optimize these cases.

+1
source

All Articles