Question

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?

Était-ce utile?

La solution 2

1 - Solve it by moving it outside. I'd recommend following the principle that all non-private types should be in their own source file.

2 - I'm less clear what the problem is here, even by moving the enum to its own file, I'd stick with your names:

public enum LineShape {Straight, Bend, Whatever};

public class FigureLine
{
    public LineShape Shape {get; private set;}
}

LineShapeis a better name than just Shape as it better describes what the enum is for (defining line styles, rather than eg 2D or 3D shapes).

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top