Defining type and property of that type inside the class

There is a problem to name property and type. Example:

public class A
{
    public class B { ... }
    public B B; // << error
}

Question 1: Why error?

I could solve it like this

public class A
{
    public B B;
}
public class B { ... } // move it outside

or like this

public class A
{
    public class B { ... }
    public B BB; // rename property
}

or even

public class A
{
    public class BB { ... } // rename type
    public BB B;
}

Question 2: How would you do it?


Moving type declaration outside is risky, because there could be several classes what semantically need same name for the type -> conflict -> strange names for some classes types or necessity to put classes inside namespaces.

Renaming it.. tricky. To example, renaming Shape type, which has to be declared for several classes drawing figures: FigureLine, FigurePoint, etc. I could call them ShapeLine, ShapePoint and so on. Or I could rename type Shape to be something like

public class FigureLine
{
    public enum LineShape {Straight, Bend, Whatever};
    public LineShape Shape {get; private set;}
}

but now if I try to use it, then it become FigureLine.LineShape - that double Line is not nice.

Renaming property... How?

Jon Skeet
people
quotationmark

Question 1: Why error?

You've got two members both called B within the same class. (A type is a member too.) You can't do that, aside from method overloading.

From section 10.3 of the C# spec:

  • The names of constants, fields, properties, events, or types must differ from the names of all other members declared in the same class.

Next:

Question 2: How would you do it?

If you want the class to be public, I'd probably make it a top-level class instead.

people

See more on this question at Stackoverflow