简体   繁体   中英

Why instantiate variable in constructor and why use property to access a variable

I have a few basic questions. I see a lot of stuff like below in code:

public class User
{
    private IList<Person> _person;
    public User()
    {
        _person = new IList<Person>();
    }

    public IList<Person> personList 
    {
        get { return _person; }
        (protected) set { _person = value; }
    }
}
  1. What is the advantage of instantiating the variable in the ctor? Why not instantiate it when declaring? You are instantiating the variable when creating an instance anyway, so why not set it during declaration?

  2. Why set the variable as private and then allow a public property to access it? (I have put protected in brackets, and I can see the advantage of this - allowing only subclasses or itself to set that property), but say you don't have protected or private set. Wouldn't it be better if you just set the variable as public?

What is the advantage of instantiating the variable in the ctor? Why not instantiate it when declaring? You are instantiating the variable when creating an instance anyway, so why not set it during declaration?

It is the same. When you declare a class level variable and instantiate it at the same line, it will inline it to the constructor (either regular or static).

For more on that see Initialize class fields in constructor or at declaration?

Why set the variable as private and then allow a public property to access it? (I have put protected in brackets, and I can see the advantage of this - allowing only subclasses or itself to set that property), but say you don't have protected or private set. Wouldn't it be better if you just set the variable as public?

Because a property, which is translated to a method call, may let you do more things inside it before setting the variable. A simple example of this would be to validate the input value is what you expect it to be.

For more differences, see Public Fields versus Automatic Properties

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