Graeme Hill's Dev Blog

The trouble with properties

Star date: 2010.274

Properties are supposed to provide encapsulation for your getter and setter logic, but they really don't enforce it. Here's what I mean:

private String _title;

public String Title
{
    get
    {
        // do custom getter stuff here
        return _title;
    }
    set
    {
        // do custom setter stuff here
        _title = value;
    }
}

The private field _title is the backing store for the property Title. The issue is that I don't want to manually create this backing store, and I really don't want it to be available anywhere in the class. I want to force anyone who edits this class to modify the value using the property, not the backing store. You don't have to create a backing store with a default property like this:

public String Title { get; set; }

This is convenient, but it beats the point entirely. I specifically want to avoid the backing store when I have custom logic in either the getter or the setter. Currently in C# and VB (and every other language I can think of for that matter) there is no way to force the use of the property internally. I think it would be ideal to have an automatic backing store that is only accessible within the getter and setter.

Am I crazy?

comments powered by Disqus