简体   繁体   中英

C# Auto-Implemented Properties - Using Inside Class

I'm looking for advice on best practices when using Auto-Implemented Properties.

I always use them if I don't need to refer to the property inside the class. However, I'm in the habit of manually adding the private property if I do need to access the property inside the class.

For example, if I had a class named Person with firstName and lastName properties and I never had to manipulate that data inside the class I would just do this:

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

However, if I needed to do something with those properties I do this:

public class Person
{
    private string _firstName;
    public string firstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    private string _lastName;
    public string lastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public void testMethod()
    {
        Debug.Print(_firstName + " " + _lastName);
    }

}

My question: Is this good practice?

No, it's pointless. You should move to fully implemented properties when you need to do more than just setting/getting a backing field.

As things stand:

Debug.Print(FirstName + " " + LastName); //convention says use UpperCamel for props

would be absolutely fine and introducing a backing-field just introduces unnecessary noise to your code.

If, instead, you want to do some validation:

public string LastName
{
    get { return _lastName; }
    set { 
        if(value.Contains("!")){
            throw new Exception("names can't contain '!'");
        }
        _lastName = value; }
}

Now you have a valid reason to move away from auto-implemented properties.

If you are simply trying to avoid the overhead of a second lookup, don't worry about it. Chances are that this will never cause performance issues, and if it does, you'll find out through measuring code timings. Trying to write optimally efficient code at the expense of clarity is a bad goal and leads to crufty code. Favour clarity every time, and when your program runs slow, you can go back and find out what caused it. Research has established that there's an extremely high chance that it won't be what you expected, so it's not an economical pursuit trying to guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM