2

Why is the following code snippet valid in C#? This is a feature of the compiler or a bug?

class A
{
    public class B : A
    {

    }
}

class C : A.B
{
    public void Foo(C.B b)
    {

    }
}

class D : A
{
    public void Foo(D.B.B.B.B b)
    {

    }
}

See Also

.NET Nested Classes

Community
  • 1
  • 1
Prankster
  • 4,031
  • 5
  • 33
  • 44
  • I don't see, why you included the C class. I think the question would be the same (and a bit shorter) if you removed it ... – MartinStettner Apr 01 '09 at 22:05
  • Because C inherits from sub-class that doesn't have 'explicit' sub-classes. Weird in its own way. – alex Apr 01 '09 at 22:38

4 Answers4

7

It's legal code, but quirky. I can dig out the bit in the spec about name resolution if you want - but it's definitely legal. I've had a conversation about a similar topic with Eric Lippert before. Strangely enough, that used D.B.B.B.B... too.

The conversation came up due to this earlier question.

The relevant section of the C# 3.0 spec is 3.8, but it's too long and involved to be worth posting here.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4
  1. D is an A
  2. A has a nested type B
  3. B is an A
  4. GOTO 2
BCS
  • 75,627
  • 68
  • 187
  • 294
1

This is rather amusing. I don't know how it could be any harm, though.

mqp
  • 70,359
  • 14
  • 95
  • 123
1

Note that the code analysis guidelines state that nested types should not be visible.

Ðаn
  • 10,934
  • 11
  • 59
  • 95