I've been fiddling with different approaches for implementing INotifyPropertyChanged.  I blogged one approach awhile back, declaring my unhappiness with the pattern.  Neil Mosafi also talked about how INotifyPropertyChanged might be an anti-pattern.  I keep searching for a better way.

At last night's Nerd Dinner, Brian Henderson was talking to Glenn Block and me about this problem.  He suggested a language feature of some sort, with perhaps the feeling of generics.  He mentioned that there really isn't anything to make properties easier, other than the automatic properties of C#, but those aren't very flexible.

I crafted a syntax that I think is what Brian was driving at.  Here's what I came up with for declaring an automatic property that implements INotifyPropertyChanged.

public NotifyPropertyChanged<int> BirthYear { get; set; }

The key for a feature like this is that you need to be able to define the "template" for these properties as a class.  I created a PropertyTemplate base class that could be used for defining these templates.

   1: public abstract class PropertyTemplate<T>
   2: {
   3:   protected T Value;
   5:   protected virtual T GetValue()
   6:     {
   7:   return this.Value;
   8:     }
  10:   protected virtual void SetValue(T value)
  11:     {
  12:   this.Value = value;
  13:     }
  14: }


Then, implementing a property template that implements INotifyPropertyChanged could be something along these lines:

   1: public class NotifyPropertyChanged<T> : PropertyTemplate<T>, System.ComponentModel.INotifyPropertyChanged
   2: {
   3:   protected override void SetValue(T value)
   4:     {
   5:   if (!object.Equals(this.Value, value))
   6:         {
   7:   this.Value = value;
   9:   if (this.PropertyChanged != null)
  10:             {
  11:   this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Value"));
  12:             }
  13:         }
  14:     }
  16:   public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
  17: }


This doesn't quite feel right, because it's not the property template that implements INotifyPropertyChanged, but rather it's the class that has the property.  I could certainly see how some sort of language feature like this would be cool though.