Wednesday, 14 January 2009

Auto-Implemented Properties and Expressing Intent

Auto-implemented properties provide a convenient way to quickly declare properties. This assumes of course that you don't need to run any logic, such as validation, in your property and that it is not read-only. Hang on, that last bit's wrong isn’t it? You can declare a read-only auto-implemented property as follows:

public bool IsReadOnly { get; private set; }

I see this quite a lot but I've got to be honest and say I'm not a big fan of using auto-implemented properties in this way. Why? Well it's only pretending to be a read-only property to the outside world. Internally the property could be modified after construction. If the intention is for the property to only be set during construction then this approach doesn’t fully reflect the intent. I’d always recommend writing code that most accurately expresses your intent, which in this case means a good old fashioned property with a read-only backing field.

private readonly bool m_isReadOnly;

public bool IsReadOnly
{
  get { return m_isReadOnly; }
}

Implementing the property this way means any attempt to set the backing field after construction will be detected by the compiler. The more bugs the compiler can detect the better J.

0 comments:

Post a Comment