Home > BCL, C#, wish > Observable Property Pattern

Observable Property Pattern

Is there something like this in the standard libraries? And if not, why not?

public class Observable<T>
{
    private T _value;

    public class ChangedEventArgs : EventArgs
    {
        public T OldValue { get; set; }
        public T NewValue { get; set; }
    }

    public EventHandler<ChangedEventArgs> Changed;

    public T Value
    {
        get { return _value; }

        set
        {
            if (!value.Equals(_value))
            {
                T oldValue = _value;
                _value = value;

                EventHandler<ChangedEventArgs> handler = Changed;
                if (handler != null)
                    handler(this, new ChangedEventArgs
                                  {
                                      OldValue = oldValue, 
                                      NewValue = value
                                  });
            }
        }
    }
}

That is, the observable property pattern as a reusable class.

This should be in the System namespace for all to enjoy. It’s a great thing when what used to be a "pattern" can now be captured in code using language features (the enabling feature in this case being generics, obviously).

Advertisements
Categories: BCL, C#, wish Tags: , ,
  1. Marcel
    September 12, 2008 at 10:07 pm

    Hmm. Nice idea. You’re right, it should be in the standard libraries.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: