Is there any C# naming convention for a variable used in a property?

后端 未结 12 1673
无人及你
无人及你 2021-01-31 07:26

Let\'s say, we have a variable, which we want named Fubar

Let\'s say that Fubar is a String!

That means, we would define F

12条回答
  •  日久生厌
    2021-01-31 08:12

    Per Microsoft's naming conventions, the proper way would be:

    private string fubar;
    public string Fubar { get { return fubar; } set { fubar = value; } }
    

    However, many people prefer to prefix the private field with an underscore to help minimize the possibility of miscapitalizing and using the field when they meant to use the property, or vice versa.

    Thus, it's common to see:

    private string _fubar;
    public string Fubar { get { return _fubar; } set { _fubar = value; } }
    

    The approach you take is ultimately up to you. StyleCop will enforce the former by default, whereas ReSharper will enforce the latter.

    In C# 6, there is new syntax for declaring default values for properties or making read-only properties, lessening the need for properties with backing fields that don't have any special additional logic in the get and set methods. You can simply write:

    public string Fubar { get; set; } = "Default Value";

    or

    public string Fubar { get; } = "Read-only Value";

提交回复
热议问题