0

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?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Mike Smith
  • 139
  • 2
  • 2
  • 12
  • 2
    for your second question - http://www.csharp-station.com/Tutorial/CSharp/lesson19 – eddie_cat Aug 15 '14 at 15:00
  • 2
    And for your first question, what if you want to pass parameters in the constructor and use them to instantiate your variable? – eddie_cat Aug 15 '14 at 15:01
  • 1
    what's the point of having your own private bedroom (variable) when your parents (public property) can just tell you go to clean it? – Marc B Aug 15 '14 at 15:01

1 Answers1

2

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

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321