user356178
user356178

Reputation:

Properties : Private ready-only backing field vs. auto-implemented + constructor

private readonly PlayerCollection players = new PlayerCollection();

public PlayerCollection Players { get { return players; } }

or

public PlayerCollection Players { get; private set; }

public MyClass()
{
    Players = new PlayerCollection();
}

Which would be preferable? Is there a context where one the of two ways is best suited?

Upvotes: 2

Views: 184

Answers (4)

MaxEmerika
MaxEmerika

Reputation: 1

From the caller's perspective, there is no difference between the two. However, in the first example, no one (not even MyClass) can set Players to a new PlayerCollection outside of the constructor. If you want the compiler to enforce this restriction, use (1). Otherwise, use (2).

Upvotes: 0

Brian
Brian

Reputation: 13517

Use the auto-implementation. You have to initialize readonly within the constructor, and there's almost never any use of using both private and readonly in conjunction with one another.

At least the auto-implementation solution lets you initialize outside the constructor, and still only allows assignment from within itself.

Upvotes: 0

Stuart Golodetz
Stuart Golodetz

Reputation: 20656

Well the first way has the advantage that the field is readonly, so you can't set it again elsewhere in the class; the second way has the advantage that it isn't, so you can. To my mind, that's a good way to decide between them - do you want the field to be readonly? If so, first way; if not, second way.

Upvotes: 3

millimoose
millimoose

Reputation: 39990

In the first case the compiler will ensure that the value can't change even from inside MyClass. Otherwise it's probably a wash, pick which you like better.

Upvotes: 0

Related Questions