Question

Is this a bug in the Microsoft C# compiler, or does the syntax serve a purpose that I'm not aware of?

class P1
{
    class P2 : P1
    {
        class P3 : P2
        {
            void Foo()
            {
                P3 p3 = this as P2.P3;
                P2 p2 = this as P3.P2;  // ?!?
            }
        };
    };
};

edit: I should mention that it compiles just fine in VS2010.

Was it helpful?

Solution

This works because your nested classes inherit from the class they're nested in.

P3 is a P2, which is a P1, which has a nested P2.

OTHER TIPS

I just pasted your code in compiler and ran the disassembler on the dll.

.method private hidebysig instance void  Foo() cil managed
{

   // Code size       6 (0x6)
      .maxstack  1
      .locals init ([0] class ProjectEuler.P1/P2/P3 p3,
       [1] class ProjectEuler.P1/P2 p2)
       IL_0000:  nop
       IL_0001:  ldarg.0
       IL_0002:  stloc.0
       IL_0003:  ldarg.0
       IL_0004:  stloc.1
       IL_0005:  ret



 }// end of method P3::Foo

So looking at the IL generated, I feel that 'this' represents p2 though more technically it is p3. But P3 is also P2 because P3 derives from P2.

This is my understanding. Please correct me if I am wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top