Leri
Leri

Reputation: 12535

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.

Upvotes: 2

Views: 184

Answers (6)

James
James

Reputation: 82096

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 e.g.

private List<string> _items;
...

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

Upvotes: 2

Henrik
Henrik

Reputation: 23324

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.

Upvotes: 2

HatSoft
HatSoft

Reputation: 11191

Personally I prefer the second version because it is less to write so I can use the time to do more complex coding.... plus in my opinion it promotes lazy development

Upvotes: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

Please go through the following question. IT seems like same ,

https://softwareengineering.stackexchange.com/questions/72495/net-properties-use-private-set-or-readonly-property

Upvotes: 1

user1485585
user1485585

Reputation: 49

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.

Upvotes: 0

Daren Thomas
Daren Thomas

Reputation: 70314

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 :)

Upvotes: 2

Related Questions