Yen's Blog

Lens, Wheels, Skates, Keyboard

Auto Property With Private Setter

Sometimes I’d like to only allow a property to be set in the constructor. Something like this:

1
2
3
4
5
6
7
8
9
10
private Foo _foo;
public Foo Foo
{
  get { return _foo; }
}

public Bar(Foo foo)
{
  _foo = foo;
}

This neat little pattern lets you do the same with fewer members (and lines of code):

1
2
3
4
5
6
public Foo { get; private set; }

public Bar(Foo foo)
{
  Foo = foo;
}