How NOT to Write Read-Only Properties
by Marshall on January 12, 2007
The other day I spent a good 45 minutes fixing a defect at work. A major portion of the time was spent trying to figure out why an object I was modifying wasn’t keeping a value for one of it’s properties. I threw the debugger into motion, stepping through the code multiple times only to find out that the object, which was declared in another assembly, had a set method that wasn’t implemented. I went into the source for the assembly in question and saw this ghastly bit of code:
public string Caption
{
get {return mCaption;}
set { }
}
This “pattern” was repeated on multiple properties in the class and on multiple classes in the assembly, so I knew that it wasn’t a mistake. So examining my simple code:
item.Caption = "Account Name";
item.Caption was never getting set and the code did not generate a compiler error. Had the Caption property not had the set { } line, my code would have thrown a compile error and I would have saved a good chunk of time debugging such a simple task.
In addition the the example above, there were a few other variations of a mis-implemented read only property, most curious was the following one, which does not make the ModifiedDate property read only, despite the presence of the [ReadOnly(true)] attribute, even though in this case, the property should probably should be a read only.
[ReadOnly(true)]
public DateTime CreatedDate
{
get { return mCreatedDate; }
set { mCreatedDate = value; }
}
Now, if you really wanted to make the Caption property read only, please, PLEASE, don’t write a setter, and don’t use attributes.
public string Caption
{
get { return mCaption; }
}
Leave your comment