Tuesday, November 15, 2005

C# Public Readonly Fields

C# public readonly fields are great. Why waste your time writing this:
public string foo;
public string Foo
get { return foo; }
When this:
public readonly string Foo;
gives you the same level of protection?

I know people simply hate public fields. The problem is this hatred has become blind hatred. A public field is dismissed without thought. In reality a private field and a getter gains me little over a public readonly field. You could argue that making a field readonly ensures it contains the value expected and is better than simply a private field with a getter.

Because I actively seek Good Citizens and Constructor Injection the field being writable only in a constructor or on the same line as the declaration is rarely a problem.

I prefer less code over blindly following a rule that simply doesn't apply to readonly fields.
Post a Comment