Posts Tagged ‘Automation Properties’

The dream of "half-automatic" Automation Properties

Friday, May 2nd, 2008

Everyone who has worked with WPF knows the interface INotifyPropertyChanged. It only defines the PropertyChanged-event, that should be called when a property’s value has been changed. The PropertyChanged-event is used by WPF’s Data Binding.

Normally a class fires the event in the set-Accessors of its properties. And that’s the problem why you can’t use Automation Properties for classes that implement INotifyPropertyChanged.

Let’s take a very simple example, a Person-class, that only contains a Name-Property:

public class Person
{
  public string Name { get; set; }
}

If you now want to implement INotifyPropertyChanged, you have to use a property backed explicitly with a private field:

public class Person:INotifyPropertyChanged
{
  private string _name;
  public string Name
  {
    get { return _name; }
    set
    {
      _name = value;
      if (PropertyChanged != null)
        PropertyChanged(this,
          new PropertyChangedEventArgs("Name"));
    }
  }
  public event PropertyChangedEventHandler PropertyChanged;
}

Wouldn’t it be nice to use a "half-automatic"-Property in the code-snippet above? The private-Field _name and the get-Accessor could be created. A keyword would be necessary to access the private-Field in the set-Accessor. I think the keyword could be autoField or something like that. If Microsoft would implement "half automatic"-Properties in C# 3.5 or 4.0, you could create the Person-class as below. But keep in mind that this is just a dream, I don’t know if something like this is planned, so the Person-class implemented like below wouldn’t work (today):

public class Person:INotifyPropertyChanged
{
  public string Name {
    get;
    set
    {
      autoField = value;
      if (PropertyChanged != null)
        PropertyChanged(this,
          new PropertyChangedEventArgs("Name"));
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

What do you think of “half-automatic”-Properties? Would it be a useful feature for you?