As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).
Another example might be a list:
public List<Foo> Items {get;private set;}
since we might call obj.Items.Add()
etc, but we would rarely assign obj.Items = ...
. However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer
hates it - to be honest for lists I mainly use:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items {get { return items;}}
which solves both of these.
As another example, contrasting:
private readonly int foo;
public int Foo {get{return foo;}}
vs
private readonly int foo;
public int Foo {get{return foo;} private set {foo=value;}}
this pattern may be useful in serialization, for example with DataContractSerializer
(with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo
), but gives the veneer of privacy to the set
.
Ultimately anything can be bypasses and assigned via reflection, so private set
is only intended to avoid accidental damage to data.