Tuesday, July 21, 2020

Sixty seconds with PostSharp

While researching AOP I came across a product called PostSharp. I've come across this before but it requires a license so I haven't dedicated any time to it. Yesterday I decided to apply for an 'influencer' licence and got one today. Within sixty seconds I decided I like it.

This is what I did...

Normally I implement INotifyPropertyChanged something like this...


using System.Windows;

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace PostSharp1
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        private string _TheText;
        public string TheText
        {
            get { return _TheText; }
            set { SetProperty(ref _TheText, value); }
        }

        public Window1()
        {
            InitializeComponent();
        }

        public bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string PropertyName = "")
        {
            if (object.Equals(storage, value))
                return false;
            storage = value;
            PropChanged(PropertyName);
            return true;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void PropChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}


Even though a lot of this code is normally derived from a base class, the syntax of the property is odious when there are a hundred of them on the page. Compare this to the same functionality when using PostSharp.

using System.Windows;

using PostSharp.Patterns.Model;

namespace PostSharp1
{
    [NotifyPropertyChanged]
    public partial class MainWindow : Window
    {
        public string TheText { get; set; }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Not having to spend hours coding highly repetitive property definitions makes the PostSharp license worth it in my opinion. And I've only been using it for sixty seconds.

No comments:

Post a Comment