Validation with PostSharp

  • .NET

PostSharp allows you to do AOP (Aspect Oriented Programming). To summarize the interest of PostSharp nothing beats a small quote:

Do you ever find yourself creating a mess by duplicating boilerplate code because of tracing, exception handling, data binding, threading, or transaction management? You're not alone. PostSharp helps clean up that mess by encapsulating these aspects as custom attributes.

In this article I will show you how to do validation on properties with PostSharp, for example to check null values. Here is what we have:

private string _foo;

public string Foo
{
    get { return _foo; }
    set
    {
        if(value == null)
            throw new Exception();
        _foo =  value;
    }
}

This is what we want to achieve:

[NotNull]
public string Foo { get; set; }

As we can see, the second version is much more consise than the first and especially much more explicit. To create a PostSharp-compatible attribute, you must inherit the Aspect class and the attribute must be serializable. In our case we do not inherit Aspect but of a child class: LocationInterceptionAspect.

[Serializable]
public class NotNullAttribute : LocationInterceptionAspect
{
    public override void OnSetValue(LocationInterceptionArgs args)
    {
        if(Equals(args.Value, null))
            throw new ArgumentNullException("value");
        base.OnSetValue(args);
    }
}

And voila, we can now decorate our properties with the NotNull attribute. As you can see it is very fast to write attributes for PostSharp.

For more information about PostSharp, see the documentation.

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Leave a reply