C# naming convention for enum and matching property

前端 未结 8 1099
鱼传尺愫
鱼传尺愫 2020-12-02 07:03

I often find myself implementing a class maintaining some kind of own status property as an enum: I have a Status enum and ONE Status property of Status type. How should I s

相关标签:
8条回答
  • 2020-12-02 07:40

    Haters of Hungarian notation and its variants be damned. I use a convention of suffixing enums with - wait for it - Enum. I consequently never have the problem you describe, waste time worrying about what to call them and the code is readable and self-descriptive to boot.

    public class Car
    {
      public enum StatusEnum
      {
        Off,
        Starting,
        Moving
      };
    
      public StatusEnum Status { get; set; }
    
    }
    
    0 讨论(0)
  • 2020-12-02 07:50

    I'll add my 1 euro to the discussion but it's probably not adding anything new.

    The obvious solution is to move Status out of being a nested Enum. Most .NET enums (except possibly some in Windows.Forms namespace) aren't nested and it makes it annoying to use for the developer consuming your API, having to prefix the classname.

    One thing that hasn't been mentioned is that flag enums according to MSDN guidelines should be pluralized nouns which you probably already know (Status is a simple enum so singular nouns should be used).

    State (enum called States) is the vocative, "Status" is the nominative of a noun that the English like most of our language absorbed from Latin. Vocative is what you name a noun for its condition and nominative is the subject of the verb.

    So in other words when the car is moving, that's the verb - moving is its status. But the car doesn't go off, its engine does. Nor does it start, the engine does (you probably picked an example here so this might be irrelevant).

    public class Car
    {
      VehicleState _vehicleState= VehicleState.Stationary;
    
      public VehicleState VehicleState 
      {
        get { return _vehicleState; }
        set { _vehicleState = value; DoSomething(); }
      }
    }
    
    public enum VehicleState
    {
        Stationary, Idle, Moving
    }
    

    State is such a generalised noun wouldn't it be better to describe what state it is referring to? Like I did above

    The type example also in my view doesn't refer to the reader type, but its database. I would prefer it if you were describing the reader's database product which isn't necessarily relevant to the type of reader (e.g. the type of reader might be forward only, cached and so on). So

    reader.Database = Databases.Oracle;
    

    In reality this never happens as they're implemented as drivers and an inheritance chain instead of using enums which is why the line above doesn't look natural.

    0 讨论(0)
提交回复
热议问题