简体   繁体   中英

Which one is better to have auto-implemented property with private setter or private field and property just getter?

My question may be a part of an old topic - "properties vs fields".

I have situation where variable is read-only for outside class but needs to be modified inside a class. I can approach it in 2 ways:

First:

private Type m_Field;
public Type MyProperty { get { return m_Field; } }

Second:

public Type MyProperty { get; private set; }

After reading several articles (that mostly covered benefits of using public properties instead of public fields) I did not get idea if the second method has some advantage over the first one but writing less code. I am interested which one will be better practice to use in projects (and why) or it's just a personal choice.

Maybe this question does not belong to SO so I apologize in advance.

The second version produces less clutter, but is less flexible. I suggest you use the second version until you run into a situation that makes the first version necessary and then refactor - changes will be local to the class anyway, so don't worry too much about that!

Generally, writing less code is a good idea. The less code you write, the less bugs you produce :)

The second one will pretty much compile down to the first one anyway, so IMO always use the second as it's less & neater code.

The only scenarios I tend to use the first approach are when I want to lazily load a property eg

private List<string> _items;
...

public List<string> Items
{
    get
    {
        if (_items == null)
        {
            _items = new List<string>();
            // load items
        }
        return _items;
    }
}

Second version is shorter, so I think it's usually better. The exception is, when the only write access occurs in the constructor. Then I prefer the first version as this allows the field to be marked as readonly .

For debugging the second is the best. Otherwise you'll have to put breakpoins at each place where you set the field. With the second you put one breakpoint on the set of the property.

我个人比较喜欢第二个版本,因为它写的少,所以我可以花些时间做更复杂的编码。。。在我看来,它还可以促进延迟开发。

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