Wednesday, November 28, 2007

Quick Tip - Read Only Automatic Properties

This is a simple little trick, which I only discovered a few weeks ago.

In the past providing public "read only" access to a member would look something like:
private string connection;

public string Connection
{
get { return connection; }
}

With Automatic Properties in C# 3.5 the code becomes:
public string Connection { get; private set; }

The neat trick is the access modifier (private) next to the set. This allow you to internally modify the member, while publicly providing "read only" access.

3 comments:

Nick said...

I've started to wonder whether this feature makes regular fields obsolete. It has always been good practice to encapsulate even private fields, however refactorings like 'encapsulate field' make the advantages a matter of syntactic consistency.

At least by adopting a properties-only approach, the argument over whether fields should be named with or without a leading underscore will finally be irrelevant!

Luke Marshall said...

Indeed! Even more since WPF data binding only works with properties - manual fields seem quite irrelevant.

Then there's the compile time (and reflection) abstraction arguments.

i.e. Field and Property access look the same, but converting a field to a property down the track involves a recompile of all associated assemblies.

Thus it's better to adopt a property only approach in general.

Nick said...

One drawback - no initialisers on declarations. e.g.:

bool IsHappy { get; set; } = true;

...doesn't have a chance of compiling :)

If you always use constructor chaining I guess that is nothing much to deal with. I do like being able to initialise fields in place though... :/