Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c# - Enum and property naming conflicts

When using a class that has an enum property, one usually gets a naming conflict between the property name and the enum type. Example:

enum Day{ Monday, Tuesday, ... }

class MyDateClass
{
   private Day day;

   public Day Day{ get{ return day; } }
}

Since only flags enums should have plural names, naming the enum "Days" is not the way to go for a non-flag enum. In the above example you could use some variation like "WeekDay" for either the enum or the property. But in the general case there are no good variations like that so you end up using properties like "FooMode" or "BarKind" for an object with enum properties of Foo and Bar type. Not so elegant.

How do you usually name enums and properties in this scenario?


Thanks for the quick responses. Another question: why is it not recommended to nest public enums, and how do you resolve the naming issues if you want to nest public enums?

class Vehicle
{
  enum Kind{ Car, Bike }

  public Kind Kind{ get{ return ... } }
}

class Meal
{
  enum Kind{ Dessert, MainCourse }

  public Kind Kind{ get{ return ... } }
}

In the scenario above, given that Meal and Vehicle share the same namespace, I can't move "Kind" outside either of the classes without renaming it MealKind and VehicleKind respectively. I like the look of

myVehicle.Kind = Vehicle.Kind.Car

But that is not what the guidlines recommend. What would be the best practice here? Never to use nested public enums and instead name them VehicleKind etc.?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no conflict. In fact, the .NET Framework style guide encourages you to do this, e.g. if you have a class that has a single property of a type (no matter if enum or class), then you should name it the same. Typical example is a Color property of type Color. It's fine, unless there are two colors - in that case both should add something to the name (i.e. BackColor and ForeColor, instead of Color and BackColor).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...