PostSharp allows you to do AOP (Aspect-Oriented Programming). To summarize what PostSharp offers, here is a quote from the project:
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 how to validate properties with PostSharp, for example to check for null values. Here is what we typically start with:
C#
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:
C#
[NotNull]
public string Foo { get; set; }
The second version is far more concise and explicit. To create a PostSharp aspect attribute, you must inherit from an Aspect class, and the attribute must be serializable. In our case, we do not inherit from Aspect directly, but from a child class: LocationInterceptionAspect.
C#
[Serializable]
public class NotNullAttribute : LocationInterceptionAspect
{
public override void OnSetValue(LocationInterceptionArgs args)
{
if(Equals(args.Value, null))
throw new ArgumentNullException("value");
base.OnSetValue(args);
}
}
We can now decorate our properties with the NotNull attribute. As you can see, writing aspects for PostSharp is quick and straightforward.
For more information about PostSharp, see the documentation.
Do you have a question or a suggestion about this post? Contact me!