Validation with PostSharp

  • Gérald Barré

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; }
        if(value == null)
            throw new Exception();
        _foo =  value;

This is what we want to achieve:

public string Foo { get; set; }

As we can see, the second version is much more concise 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.

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

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.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub