Why I think Microsoft shouldn’t make observable properties part of the C# Language specification.

INotifyPropertyChanged, how I love you implement you in every object over and over. How I can't make you a reusable base class because it causes me to break important inheritance hierarchies. I love it, but I hate it because it is one of the most repetitive things I do in programming. It's absolutely vital for data-binding in various frameworks like Windows Forms and Windows Presentation Foundation, but I can't help but think "why isn't this a core part of the C# language?".

My solution would to be to add a contextual keyword to the C# language specification, and call it observable. It would be used like this.

public observable class A
{
    public observable String PropertyName
    {
        get;
        set;
    }
}

And this is what I see the compiler generating.

public class A : INotifyPropertyChanged
{
    public String PropertyName
    {
        get
        {
            return propertyNameField;
        }
        set
        {
            propertyNameField = value;
            OnNotifyPropertyChanged("PropertyName");
        }
    }

    public PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

How this should work is that when you compile your class, the compiler sees the observable keyword on the class and implements INotifyPropertyChanged interface for the class. Next, it sees any properties that are also observable and injects a call to OnPropertyChanged with the appropriate parameters. Okay, so this is a pretty good argument for implementing this, but that isn't the title of my post.

The problem with this, albeit requested or thought of by many programmers over the years, is you have zero control over this. I'll list out some of the limitations.

  • You can't put a lock in OnPropertyChanged(String)
  • You can't put any custom code in OnPropertyChanged(String)
  • You can't use this with .NET 4.5 caller attributes
  • You can't control the accessibility of OnPropertyChanged(String)
  • You can't control whether OnPropertyChanged(String)
  • can be overridden or not.

In general, this is a bad idea. You could potentially solve all of these problems with compiler flags, but I believe this creates language and compiler bloat, both of which I disagree with. I'm sure the C# language team has already visited this discussion, Anders himself has discussed it at one point. I think the real solution would be to think outside of the box and how to ease-the-pain of implementing the interface instead.

Leave a Comment