It has been one more successful iteration (we’re on a 3-week cycle here) and on Monday we’ve successfully released PostSharp 4.2 Preview 4, available for download on our website and on NuGet (make sure to enable the pre-release option as usually). This should be our last Preview release for PostSharp 4.2; we’re now heading toward the RC.

What’s new in PostSharp 4.2

In the previous blog posts, I already announced the following improvements included in previous previews of PostSharp 4.2:

  • Support for Visual Basic
  • Ready-made patterns: amazing performance improvements
  • Ready-made patterns: support for System.Collections.Immutable
  • Ready-made patterns: support for programmatic rules
  • Thread-safety policy
  • INotifyPropertyChanged: support for INotifyPropertyChanging
  • Module initializers
  • OnAspectsInitialized advice

Today, I’m announcing the following new features:

  • Code saving metrics
  • Manual code metrics
  • Customizable advice descriptions

Code Metrics

How much code do you really save using PostSharp? This is a central question: indeed, the total cost of ownership of custom-built software is roughly in linear dependence to its number of lines of code. We tried to answer this question statistically and very approximately based on data from our CEIP data and discovered it was not uncommon to save 20%. But yet, there were too many guesses, and we weren’t satisfied with the answer.

So we decided to bake code metrics directly into PostSharp, so you can know how much you save with PostSharp.

There are two locations where you can see code savings in Visual Studio: in tooltips, and in a new tool window.

Code Savings in Tooltips

The first location where you will find code saving metrics is in the PostSharp-augmented tooltip. You will find detailed information about how individual aspects and advices affect the current piece of code:

Code Metrics Tool Window

Tooltips are great when you want a detailed view, but sometimes you also need to get the big picture. That’s why we’re also displaying project-level metrics in a separate tool window. To open it, click on PostSharp / PostSharp Metrics in the Visual Studio menu.

You can then see how much manual lines of code you have in each project, and how much additional code you would have to write if you didn’t use PostSharp:

About Lines of Code

Developers generally hate lines of code as a metric. I think there are two elements we need to address in this criticism: the intended use of the metric, and the algorithm used to compute the metric.

There are many bad uses of software metrics. Comparing productivity of individual developers is one of the worse. However, lines of source code is a decent metric to estimate the size of a project. Empirical studies show, ex post, a strong correlation between the number of lines of code and the total development effort. The intended use of metrics computed by PostSharp is to let you evaluate how efficiently you’re using aspects in your project.

People often argue that the LOC metric is highly sensitive to coding style (text formatting). PostSharp’s algorithm is absolutely insensitive to formatting. PostSharp does not directly counts lines of code in your text files, it actually sums the following:

  • Debugging sequence points: every possible location of a breakpoint (or any possible step of an F10) is considered a line of code (minus two points per method, which are for the opening and closing brackets and don’t really map to source code). This is a very logical and natural way of computing the size of a program. It is quite close to the number of instructions.
  • Declarations: we count one line of code per type, method, field, property, property getter, property setter, event, event adder, event remover – unless the declaration is compiler-generated. Abstract members are also counted because they should also be considered source code. Property and event accessors without body are not counted. Custom attributes are not counted because they are considered as modifiers, like readonly or private.

Therefore we can say that PostSharp computes the number of logical lines of code in your project. I believe it’s the best size metric possible.

Ready-Made Patterns

We added code saving information to all our ready-made patterns. It was sometimes difficult to take a decision on how many LOC to put because automatic code generation strategies greatly differ from manual generation strategies. When putting LOC numbers, we tried to answer the question: “How much code would I have to write if I had to implement the feature manually with the fewest number of LOC possible?”. This gives us much lower numbers than what we actually inject.

In general, you can consider that the code saving estimates for ready-made patterns are a very conservative estimate. You can convince yourself by looking at the tooltips: you will see that we actually do not push LOC saving for most advices.

You may be surprised to see how much code is generated by thread-safety aspects. First let me repeat that the estimate displayed in Visual Studio is very conservative for thread safety. However, much of this code is used by run-time validation, which is typically included in debug builds but not in release builds. For instance, for our PostSharp Tools solution, PostSharp saves 16% of code in debug build but only 8% in release build. That means that 8% is an overhead added to the debug build in order to deterministically detect potential model violations (and prevent data races). Does it mean that these 8% have no value? No of course, they do have enormous value, because they guarantee the thread safety of our release build.

Adding Code Saving Information to Your Aspects

Ready-made aspects are just a part of the story. Your custom aspects also participate in avoiding boilerplate code. To benefit from accurate code saving information, you will need to tell PostSharp how much lines are avoided every time your aspect is used.

The easiest way is to add the [LinesOfCodeAvoided] attribute to your aspect class.

public sealed class DispatchedMethodAspect : MethodInterceptionAspect
// Details skipped.

The [LinesOfCodeAvoided(2)] custom attribute above instructs PostSharp to consider that 2 lines of code have been saved every time DispatchedMethodAspect is applied to a method.

If you have composite aspects in your code (the ones composed from several advices of the PostSharp.Aspects.Advices namespace), you can get more precise estimates by specifying how many lines of code are saved every time an advice is applied.  Simply set the LinesOfCodeAvoided property of the advice custom attribute.

[OnLocationSetValueAdvice(LinesOfCodeAvoided = 2)]
[MethodPointcut( "SelectFields" )]
public void OnFieldSet( LocationInterceptionArgs args )
  // Details skipped.

In the code above, PostSharp will consider that 2 lines of code have been avoided every time that the OnFieldSet advice has been applied to a field.

Customizable Advice Descriptions

In the screenshots above, you can see that the description of advices now makes sense: the text actually says what the advice is doing. In previous versions of PostSharp, you would have got some text like “the field is intercepted by OnFieldSet”, which was not very useful if you didn’t write the aspect yourself. Now, you can add a custom description to your advices so the tooltips make sense.

To add a custom description to your advices, simply set the Description of the advice custom property. For instance:

[OnLocationSetValueAdvice(LinesOfCodeAvoided = 2, 
                           Description = "Validates that the current thread has access to the object")]
[MethodPointcut( "SelectFields" )]
public void OnFieldSet( LocationInterceptionArgs args )
  // Details skipped.


Lies, damned lies, and code metrics. Counting logical lines of code is pretty straightforward and reliable, but it’s much more difficult and controversial to estimate how much code you avoided writing manually thanks to PostSharp. We understand there isn’t one right way to compute this estimate so we tried at least an educated but conservative guess.

We hope it will give you an idea of how PostSharp is useful in your projects.

However, keep in mind that reducing boilerplate is just one of the many benefits of PostSharp. According to most long-time customers, PostSharp’s first benefit is that source code is simpler, easier to read and understand – especially by new team members. And this is much more difficult to quantify.

Happy PostSharping!



It has been a few weeks since the release of PostSharp 4.2 Preview 1. Today, I’m happy to announce new features and improvements to PostSharp. If you want to discover them, you can download PostSharp from our website or from NuGet (make sure to enable pre-releases).

What was new in PostSharp 4.2

In the previous blog post, I already announced the following improvements included in PostSharp 4.2 Preview 1:

  • Support for Visual Basic
  • Amazing performance improvements in ready-made patterns
  • Other improvements in threading models

Today, I’m announcing the following new features:

  • Thread-safety policy
  • Ready-made patterns: support for System.Collections.Immutable
  • Ready-made patterns: support for rules
  • Module initializers
  • Support for INotifyPropertyChanging
  • OnAspectsInitialized advice

How we dogfooded our own threading models

Most of the improvements we are publishing in this release stem from dogfooding our threading models into PostSharp Tools for Visual Studio. I’m proud to say that we now have a multithreaded VS extension without a single lock or event. Now that all threading assumptions have been made explicit and declarative, the code is much cleaner and easier to understand.

Frankly, the experience was both exciting and awkward. Exciting because the result is amazing. Awkward because we filed more than 50 bugs, enhancements and user stories in the process – principally usability issues or improvements. Most of these tickets are addressed in PostSharp 4.2 Preview 3.

Thread-safety policy

Suppose that you have a large solution with hundreds of classes and you want to apply PostSharp thread safety to it. Typically, you would go through all classes and apply one of the PostSharp threading models. But how do you know you didn’t forget anything?

The short answer:

[assembly: ThreadSafetyPolicy]

When added to a project, the thread-safety policy shall emit a warning whenever it detects:

  • A class without threading model
  • A static field that is mutable or of a non thread-safe type.

Having none of these warnings is not a 100% guarantee that your application is thread-safe. However, it catches the most common omissions. Once a class is assigned to a threading model, thread safety becomes the responsibility of the threading model itself, not of the thread-safety policy.

The thread-safety policy is built using PostSharp Architecture Framework.

Ready-made patterns: support for System.Collections.Immutable

Let’s face it: immutability is a great concept. It allows for excellent runtime performance and, most importantly, makes it easier to think about the semantics of your API. PostSharp provides the [Immutable] threading model to ensure your custom classes are immutable. Previously, you should have used an AdvisableCollection inside your immutable objects. However, the AdvisableCollection class is far from being as fast and convenient as immutable collections. That’s why we added genuine support for System.Collections.Immutable in PostSharp ready-made patterns.

So you can now mix PostSharp’s threading models with Microsoft’s immutable collections to build code that’s thread-safe, highly readable, and still fast enough.

Here is an example of class that has been ported to [Immutable]. Note that we did not completely refactor the solution to use immutable collections, that’s why inputs and outputs of the class are still mutable arrays.

public class BasicWizardProcess : IWizardProcess
    [Child(ItemsRelationship = RelationshipKind.Reference)]
    private ImmutableArray wizardParts;

    public BasicWizardProcess( params IWizardPart[] wizardParts ) 
        this.wizardParts = ImmutableArray.Create(wizardParts);
    public IWizardPart[] GetParts( IWizardController controller )
        foreach ( IWizardPart part in this.wizardParts )
            part.Controller = controller;
        return this.wizardParts.ToArray();

Ready-made patterns: support for rules

Threading models and undo/redo require you to annotate your object model with a parent-child structure using the [Child] and [Reference] attributes. When you have a reference-type field, PostSharp needs to know whether it is a reference or a child (i.e. whether it is an association or an aggregation/composition). As a design decision, PostSharp does not assume that unannotated fields are automatically references.

There are times when this design is unusable. For instance, there is no way to annotate fields generated by the WinForms or XAML designers.

Starting from PostSharp 4.2, it becomes possible to assign the role of a field programmatically, by rule. A rule is simply a class derived from FieldRule. You need to register the rule using the [RegisterFieldRule] custom attribute.

The following code shows our internal rules for WinForms. Note that this rule is automatically registered so there’s no need for [RegisterFieldRule] in this specific case.

internal sealed class WinFormsFieldRule : FieldRule
    public override RelationshipKind? GetRelationshipKind(FieldInfo field)
        if ( IsDerivedFrom(field.DeclaringType, "System.Windows.Forms.Control") && ( field.Name == "components" 
|| IsDerivedFrom( field.FieldType, "System.Windows.Forms.Control") )) { return RelationshipKind.Reference; } else { return null; } } }

The benefits of rules is that you don’t have to explicitly use custom attributes everywhere. We will continue to require custom attributes if no rule is defined because we believe it’s a good practice to force developers to think about the role of a field. However, you can now easily implement a rule that makes all fields references by default. Note that custom attributes always have priority over rules.

Note also that rules are not yet integrated with the UI.

Module initializers

Ever wanted to execute code immediately when an assembly is loaded? Static constructors are not enough: you need a module initializer. VB has them, but C# does not. PostSharp 4.2 fixes this with the [ModuleInitializer(int)] custom attribute.

Just add the custom attribute to a static public/internal void parameterless method. Here is an example. It also demonstrates how we test PostSharp internally:

public static class Program
    static StringBuilder trace = new StringBuilder();

    public static int Main()
        if (trace.ToString() != "0;1;2;")
            return 1;

        return 0;

    public static void Method0()

    public static void Method1()

    public static void Method2()


Support for INotifyPropertyChanging

PostSharp has supported INotifyPropertyChanged for a long time now. It now also supports INotifyPropertyChanging.

The feature is a bit tricky because INotifyPropertyChanging is not portable, but our [NotifyPropertyChanged] aspect is. Here is how to proceed:

  1. Your target class needs to implement INotifyPropertyChanging manually and it has to define a void OnPropertyChanging(string) method (typically protected). PostSharp will emit the event through the OnPropertyChanging method.
  2. If you want to support dependencies of objects that implement INotifyPropertyChanging but do not have the [NotifyPropertyChanged] aspect, you need to implement an INotifyPropertyChangingAdapter and register it using NotifyPropertyChangedServices.PropertyChangingAdapter.

The procedure is a bit cumbersome so we (or you) could create a non-portable [NotifyPropertyChanging] aspect that would encapsulate this for a specific platform.

OnAspectsInitialized advise

How can you execute code after all aspects on a class have been initialized? Previously, you could not do that in a simple and reliable way. We decided to fix that, simply, because we needed it to fix a few bugs :) The solution is now to use [OnAspectsInitializedAdvice]:

public void OnAspectsInitialized(AspectInitializationReason reason)


PostSharp 4.2 makes threading models usable in complex, real-world applications. We ate our own dogfood. We were scared by the number of small usability issues we encountered, but so relieved that our initial design was correct and robust.

Happy PostSharping!


It’s a pleasure to announce the first preview release of PostSharp 4.2, available for download on our website and on NuGet (make sure to enable pre-releases).

PostSharp 4.2 Preview 1 brings the following improvements:

  • Support for Visual Basic (ready)
  • Runtime performance improvement in ready-made patterns (ready)
  • Threading models improvements (ready)
  • INotifyPropertyChanging and support for Xamarin Forms
  • Code saving metrics

In this post, I will just describe the improvements that are already integrated in PostSharp 4.2 Preview 1.

Visual Basic Support

Initially, PostSharp was equally available to C# and VB because they both compile to MSIL, the level at which PostSharp works. However, with time, we developed language-specific features, and made them available only for C#. Today, thanks to the Roslyn project, we are able to bring these features to VB as well:

  • File/line/column positioning of error messages now works also for VB.
  • PostSharp Tools for Visual Studio now supports VB, but only under Visual Studio 2015.
  • The PostSharp compiler now contains more tests that are specific to VB.

VB is now equally supported as C#. Again, I would like to remind that this is thanks to the Roslyn project, which makes it much easier for everybody to support the VB language. No, VB is not dead, Roslyn gives it a second life.

Amazing performance improvement in ready-made patterns

Amazing means, really, a huge difference. In the case of INotifyPropertyChanged, we are now 10 times faster than PostSharp 4.1. This seems a bit embarrassing and requires a few words of explanation.

As we at PostSharp are writing more and more complex aspects, we have been hitting the performance barrier of the current design of the PostSharp Aspect Framework. This design, dating from 2010, did not envision aspects that would include so many transformations. So, its runtime performance was good (even excellent) for the scenarios it was designed for, but with PostSharp 4.0 we seriously started to reach its limits. The root cause of performance limitations is that the PostSharp currently requires a context object (typically OnMethodBoundaryArgs or LocationInterceptionArgs) to be passed from the target code to the aspect code, and this object is allocated on the heap. This creates significant pressure on garbage collection if the aspect is applied to methods called very often, for instance on property getters. Although this technique is way faster than PostSharp’s competition and by the scenarios targeted by this competition (like logging or transaction handling), this is too slow to serve our new ambitions of bringing a solution to thread safety or INotifyPropertyChanged.

So, we are currently investing in PostSharp Aspect Framework so that aspect code receives its context on the stack (as parameters) and not on the heap. The performance gain is just amazing.

Let me be very clear here: we are not advertising our work on PostSharp Aspect Framework as a feature of PostSharp 4.2. This is a huge work, and we will not finish it in PostSharp 4.2. We only developed and tested the features required by our own ready-made pattern implementations. The “modern” aspect framework will not be documented in PostSharp 4.2, and will justify its own major version, probably PostSharp 5.0. In the meantime, you can try the new undocumented APIes, but at your own risks, and without right to support or bug fixes.

Threading models improvements

In PostSharp 4.2, we would like to finish a few items that did not fit into the 4.0 releases. Threading models were a huge innovation and required a massive amount of work and testing. In the rush to close the 4.0 release (because releasing is a feature, too), we reserved a few work items for later, and now it’s time to go back to them.

The most significant improvement is that we no longer block on async methods. So, if you have an async method in a [Synchronized] or [ReaderWriterSynchronized] class, we will now await for the lock. Previously, we would wait for it synchronously, and you would partially lose the benefit of having an async method. This was a very complex work, relying both on some improvements of PostSharp Aspect Framework that will be made public in PostSharp 5.0, and on awaitable threading primitives. The good thing is that we did the hard work so that you can focus on business code.

Note that there is still a case when we wait synchronously instead of asynchronously, but this is a minor one: after executing a [Yielder] method in a [ReaderWriterSynchronized] class.

The second improvement is that we now have an AdvisableHashSet class in addition to AdvisableCollection, AdvisableKeyedCollection and AdvisableDictionary.

Finally, runtime performance of threading models is now dramatically better as described in the previous section.


Besides support for Visual Basic and code metrics (yet to be released), PostSharp 4.2 is an incremental improvement release. Yet, its runtime performance improvements are so huge that you will want to give it a try.

More at the end of next iteration.

Happy PostSharping!