Click here to Skip to main content
12,755,986 members (35,460 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15.8K views
21 bookmarked
Posted 30 Jan 2010

A C# Property Class

, 7 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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:

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.

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.

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).

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:

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:

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);
  }
}  

License

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

Share

About the Author

Don Kackman
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

You may also be interested in...

Comments and Discussions

 
GeneralBeautiful! Pin
xzz019521-Oct-10 15:27
memberxzz019521-Oct-10 15:27 
GeneralYou have to love generics! Pin
Diamonddrake31-Jan-10 13:37
memberDiamonddrake31-Jan-10 13:37 
GeneralRe: You have to love generics! Pin
Don Kackman5-Feb-10 11:16
memberDon Kackman5-Feb-10 11:16 
GeneralNot a good idea Pin
tonyt30-Jan-10 20:54
membertonyt30-Jan-10 20:54 
GeneralRe: Not a good idea Pin
Don Kackman31-Jan-10 14:21
memberDon Kackman31-Jan-10 14:21 
GeneralRe: Not a good idea Pin
Jason Christian1-Feb-10 19:41
memberJason Christian1-Feb-10 19:41 
GeneralRe: Not a good idea [modified] Pin
Don Kackman7-Feb-10 11:50
memberDon Kackman7-Feb-10 11:50 
GeneralRe: Not a good idea Pin
tonyt8-Feb-10 2:43
membertonyt8-Feb-10 2:43 
GeneralRe: Not a good idea Pin
Don Kackman9-Feb-10 14:41
memberDon Kackman9-Feb-10 14: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 7 Feb 2010
Article Copyright 2010 by Don Kackman
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid