Click here to Skip to main content
Licence CPOL
First Posted 30 Jan 2010
Views 9,003
Bookmarked 21 times

A C# Property Class

By Don Kackman | 7 Feb 2010 | Technical Blog
A generic class to encapsulate properties with notification events

1

2

3
2 votes, 22.2%
4
7 votes, 77.8%
5
4.79/5 - 9 votes
μ 4.79, σa 0.89 [?]
A Technical Blog article. View original blog here.[^]

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)

About the Author

Don Kackman

Team Leader
Starkey Laboratories
United States United States

Member
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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralBeautiful! Pinmemberxzz019515:27 21 Oct '10  
GeneralYou have to love generics! PinmemberDiamonddrake13:37 31 Jan '10  
GeneralRe: You have to love generics! PinmemberDon Kackman11:16 5 Feb '10  
GeneralNot a good idea Pinmembertonyt20:54 30 Jan '10  
GeneralRe: Not a good idea PinmemberDon Kackman14:21 31 Jan '10  
GeneralRe: Not a good idea PinmemberJason Christian19:41 1 Feb '10  
GeneralRe: Not a good idea [modified] PinmemberDon Kackman11:50 7 Feb '10  
GeneralRe: Not a good idea Pinmembertonyt2:43 8 Feb '10  
GeneralRe: Not a good idea PinmemberDon Kackman14:41 9 Feb '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web02 | 2.5.120210.1 | Last Updated 7 Feb 2010
Article Copyright 2010 by Don Kackman
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid