C# Field Naming Guidelines?

后端 未结 17 1277
天命终不由人
天命终不由人 2020-12-02 16:37

I am going to be working on a bit of C# code on my own but I want to make sure that I follow the most widely accepted naming conventions in case I want to bring on other dev

17条回答
  •  执笔经年
    2020-12-02 17:35

    Follow the Microsoft Naming Guidelines. The guidelines for field usage indicate that it should be camelCase and not be prefixed. Note that the general rule is no prefix; the specific rule is not to prefix to distinguish between static and non-static fields.

    Do not apply a prefix to field names or static field names. Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields. For example, applying a g_ or s_ prefix is incorrect.

    and (from General Naming Conventions)

    Do not use underscores, hyphens, or any other nonalphanumeric characters.

    EDIT: I will note that the docs are not specific with regard to private fields but indicate that protected fields should be camelCase only. I suppose you could infer from this that any convention for private fields is acceptable. Certainly public static fields differ from protected (they are capitalized). My personal opinion is that protected/private are not sufficiently different in scope to warrant a difference in naming convention, especially as all you seem to want to do is differentiate them from parameters. That is, if you follow the guidelines for protected fields, you'd have to treat them differently in this respect than private fields in order to distinguish them from parameters. I use this when referring to class members within the class to make the distinction clear.

    EDIT 2

    I've adopted the convention used at my current job, which is to prefix private instance variables with an underscore and generally only expose protected instance variables as properties using PascalCase (typically autoproperties). It wasn't my personal preference but it's one that I've become comfortable with and probably will follow until something better comes along.

提交回复
热议问题