Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegantly Handle Repetitive Property Code in C#

The language shortcut

public string Code
{
    get;
    set;
}

saves a bit of typing when defining trivial properties in C#.

However, I find myself writing highly repetitive, not-quite-as-trivial property code that still follows a clear pattern e.g.

public string Code
{
    get { return code; }
    set 
    {
        if (code != value)
        {
            code = value; 
            NotifyPropertyChanged("Code");
        }
    }
}

I can certainly define a Visual Studio snippet to reduce typing. However, if I need to add something to my pattern, I have to go back and change quite a bit of existing code.

Is there a more elegant approach? Is a snippet the best way to go?

UPDATE:

As a quick improvement for right now, I have edited (after making a backup)

C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring\EncapsulateField.snippet

(path is for VS 2010)

to reflect my current pattern. Now, the built-in refactoring tool uses my template to create a property from a field. Drawbacks: Global change for Visual Studio, cannot retroactively change existing property code.

like image 560
Eric J. Avatar asked May 11 '10 04:05

Eric J.


1 Answers

This is know as Aspect Oriented Programming (AOP).

Scott Hanselman recently did an interview with the creator of LinFu, Philip Laureano on this topic. (link)

There are a number of AOP tools out there, depending on your needs.

  • LinFu
  • PostSharp
  • DynamicProxy
  • Unity Interception Extension (part of Unity)

And finally, some implementations of an INotifyPropertyChanged class using the above tools:

  • Unity
  • DynamicProxy
  • PostSharp 1, 2, 3, 4

Update 2013: Since this original answer I've come across another solution that does everything I need very easily.

PropertyChanged.Fody (formerly NotifyPropertyWeaver) is a post-compile IL weaver which will automatically insert property changed code for you. This is now my preferred solution for INotifyPropertyChanged.

like image 91
Cameron MacFarland Avatar answered Sep 27 '22 23:09

Cameron MacFarland