Click here to Skip to main content
15,881,938 members
Articles / Programming Languages / C#

A C# Property Class

Rate me:
Please Sign up or sign in to vote.
4.79/5 (9 votes)
7 Feb 2010CPOL1 min read 22K   21   9
A generic class to encapsulate properties with notification events

Soon after starting work in C#, there were a couple of code patterns that arose that made me miss the good ol' C/C++ pre-processor. One of these is the basic pattern of a class property with change notification.

You've got a class and you want the state of its properties to be observable via events. How many times have you written the following bit of code in some form or the other? Automatic properties help when you don't need notification, INotifyPropertyChange abstracts that event a little. Still, a lot of boilerplate.

C#
int _age;

public event EventHandler AgeChanged;

protected virtual void OnAgeChanged()
{
  if(Changed != null)
    Changed(this, EventArgs.Empty);
}

public int Age
{
  get{ return _age; }
  set
  {
    if(value != age)
    {
      value = age;
      OnAgeChanged();
    }
  }
}   

Having written a fair amount of MFC in the years prior I really wanted to be able to do something like:

C#
DECLARE_PROPERTY(Age, int)

and have a fancy macro that would handle the boiler plate. Alas there is no macro pre-processor in C#-land.

The introduction of .NET generics opens up the opportunity to model a class property as a class itself, while retaining type safety and the same assignment semantics as intrinsic types. So this little class (and a derived class with a cancellable event) has become a handy part of my toolbox.

C#
public class Property<T>
{
  protected T _value = default(T);

  public Property()
  {
  }

  public Property(T value)
  {
      _value = value;
  }

  public event EventHandler Changed;

  public virtual T Value
  {
    get { return _value; }
    set
    {
        if ((value != null && !value.Equals(_value)) ||
            (_value != null && !_value.Equals(value)))
        {
            _value = value;
            OnChanged();
        }
    }
  }

  protected virtual void OnChanged()
  {
    if (Changed != null)
        Changed(this, EventArgs.Empty);
  }

  public static implicit operator Property(T value)
  {
    return new Property(value);
  }
}   

Using it is just a matter of declaring a public field on a class declaration.

C#
class Person
{
  public readonly Property<int> Age = new Property<int>();

  public readonly Property<string> Name = new Property<string>();
}  

Interacting with the properties looks just like an intrinsic (due to the implicit two way cast operators on the Property class).

C#
Person don = new Person();
don.Name.Value = "Don";
don.Age.Value = 41;

if (don.Age > 40)
  Console.WriteLine("Ooooooold");

with the difference that every property now comes with a built in Changed event:

C#
don.Age.Changed += new EventHandler(Age_Changed);

So anyway, I've found this to be a handy pattern and thought perhaps you might as well.

P.S.: The cancellable derived class looks like this:

C#
class CancellableProperty<T> : Property<T>
{
  public CancellableProperty(T value)
    : base(value)
  {
  }

  public event CancelEventHandler Changing;

  public override T Value
  {
    set
    {
        if ((value != null && !value.Equals(_value)) ||
            (_value != null && !_value.Equals(value)))
        {
            CancelEventArgs args = new CancelEventArgs(false);
            OnChanging(args);
            if (args.Cancel == false)
            {
                _value = value;
                OnChanged();
            }
        }
    }
  }

  protected virtual void OnChanging(CancelEventArgs args)
  {
    if (Changing != null)
        Changing(this, args);
  }
}  

This article was originally posted at http://spookycoding.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Starkey Laboratories
United States United States
The first computer program I ever wrote was in BASIC on a TRS-80 Model I and it looked something like:
10 PRINT "Don is cool"
20 GOTO 10

It only went downhill from there.

Hey look, I've got a blog

Comments and Discussions

 
GeneralBeautiful! Pin
Your Display Name Here21-Oct-10 14:27
Your Display Name Here21-Oct-10 14:27 
GeneralYou have to love generics! Pin
Diamonddrake31-Jan-10 12:37
Diamonddrake31-Jan-10 12:37 
GeneralRe: You have to love generics! Pin
Don Kackman5-Feb-10 10:16
Don Kackman5-Feb-10 10:16 
GeneralNot a good idea Pin
tonyt30-Jan-10 19:54
tonyt30-Jan-10 19:54 
GeneralRe: Not a good idea Pin
Don Kackman31-Jan-10 13:21
Don Kackman31-Jan-10 13:21 
GeneralRe: Not a good idea Pin
Jason Christian1-Feb-10 18:41
Jason Christian1-Feb-10 18:41 
GeneralRe: Not a good idea [modified] Pin
Don Kackman7-Feb-10 10:50
Don Kackman7-Feb-10 10:50 
GeneralRe: Not a good idea Pin
tonyt8-Feb-10 1:43
tonyt8-Feb-10 1:43 
GeneralRe: Not a good idea Pin
Don Kackman9-Feb-10 13:41
Don Kackman9-Feb-10 13:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.