2

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.

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
  • Thanks, I apologize that I didn't see http://stackoverflow.com/questions/455928/net-nested-classes earlier, and this is basically similar. – Glenn Slayden Dec 02 '10 at 23:52

2 Answers2

5

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.

kristian
  • 22,731
  • 8
  • 50
  • 78
  • 1
    Note that Resharper (and possibly VS) will warn you if you refer to a static member via a derived class, which helps to alleviate confusion like this. – Dan Bryant Dec 02 '10 at 23:52
0

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.

AlwaysAProgrammer
  • 2,927
  • 2
  • 31
  • 40