C# Field Naming Guidelines?

后端 未结 17 1272
天命终不由人
天命终不由人 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:29

    _camelCase for fields is common from what I've seen (it's what we use at our place and Microsoft prefer for the .NET Runtime).

    My personal justification for using this standard is that is is easier to type _ to identify a private field than this.

    For example:

    void Foo(String a, String b)
    {
        _a = a;
        _b = b;
    }
    

    Versus

    void Foo(String a, String b)
    {
        this.a = a;
        this.b = b;
    }
    

    I find the first much easier to type and it prevents me from ever accidentally assigning to the parameter called a instead of this.a. This is reinforced by a Code Analysis Maintainability Rule that states:

    • CA1500 Variable names should not match field names.

    My other reason, is that this. is optional (Visual Studio / Code prompts you to remove them) if it doesn't collide with a local variable or parameter name, making knowing which variable you are using harder. If you have an _ at the start of all private fields, then you always know which is a field and which is has local scope.

提交回复
热议问题