Why I do not recommend using an underscore in C # _ beginning to represent a private field

My official documents in C # using the property to see this code:

public class Date
{
    private int _month = 7;  // Backing store

    public int Month
    {
        get => _month;
        set
        {
            if ((value > 0) && (value < 13))
            {
                _month = value;
            }
        }
    }
}

This code where _monthbegins with an underscore, used to represent private. What will it do this problem?

  • Mixed use project hump nomenclature and underscores nomenclature, disrupting the line of sight to read the code
  • Unlike other languages (such as JavaScript), C # itself has provided private modifier, then do not need to underline _repeat represents private
  • Underline _has been used to represent abandoned yuan function, is not it confusing?

In fact, I simply use the hump nomenclature, not underlined _at the beginning, there will not be any problems. code show as below:

public class Date
{
    private int month = 7;  // Backing store

    public int Month
    {
        get => month;
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}

It looks more concise and easier to understand. Here, also from the official document auto-implemented properties in code is very good:

// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
    // Auto-implemented properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    // Constructor
    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }

    // Methods
    public string GetContactInfo() { return "ContactInfo"; }
    public string GetTransactionHistory() { return "History"; }

    // .. Additional methods, events, etc.
}

class Program
{
    static void Main()
    {
        // Intialize a new object.
        Customer cust1 = new Customer(4987.63, "Northwind", 90108);

        // Modify a property.
        cust1.TotalPurchases += 499.99;
    }
}

In fact, the only hump nomenclature, but do not expose the fields and use the property get / set accessor, or simply played a better variable names, you can always find ways to avoid using the underscore _at the beginning.

Published 26 original articles · won praise 53 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_37925422/article/details/104547879