Tag Archives: Roslyn

A few important Roslyn API helpers

The Roslyn API as implemented in RC2 has been out for a few months now and is likely to remain largely unchanged while they’re working on getting it released officially. I think it might be time to do a little write-up and identify the key-components of that API that you likely want to use when building your own diagnostics, syntax writers or anything else possible with the platform. Do note that I am approaching this with only a background in writing diagnostics so I might be missing out on helpers from a different spectrum of the API.

I, too, still come across a new API which I wasn’t aware of before so if you know of something that’s not here, let me know.


If you’ve ever tried to create your own syntax node, you’ll have noticed that you can’t just new() it up. Instead, we use the SyntaxFactory class which provides methods to create just about every kind of node you could imagine. A particularly interesting method here is SyntaxFactory.Parse*. This can take away a lot of pain involved in manually creating syntaxnodes. For example in one of my diagnostics I wanted to create a condition that checks a certain variable and compares it to null. I could either create a BinaryExpression, set its operator to SyntaxFactory.Token(SyntaxKind.ExclamationEqualsToken), create an identifier using SyntaxFactory.Identifier and eventually add the null token using SyntaxFactory.Token(SyntaxKind.NullKeyword).

Or I could just write SyntaxFactory.ParseExpression($"{identifier} != null");.

I won’t pretend there aren’t any performance implications of course but sometimes it’s hard to contain myself when I can write something really readable like this. I know, shame on me.


This one is closely related to a SyntaxNode but represents certain aspects of it: the SyntaxNode.Modifiers property, in the case of – say – a method, will be a list of SyntaxToken objects. These, too, are created using SyntaxFactory.Token().


This enum represents certain aspects of the syntax. Think of keywords, carriage returns, semicolons, comments, certain expressions or statements like a++, etc. You will also use this to construct certain tokens by passing them as an argument to SyntaxFactory.Token(SyntaxKind). Notice how the API is coming together? Eventually, it will allow you to create a new syntax tree with a fairly fluent API — and which is very readable!


We all like our code properly formatted and thankfully, we can let Roslyn do that for us! There are a few approaches here: if you’re using a Code Fix then all you need to do is tell Roslyn which nodes you want formatted and the Code Fix will call the formatter for you when reconstructing the tree. You can do this by calling .WithAdditionalAnnotations(Formatter.Annotation) on any node you want formatted. If you’re in an environment that doesn’t do this for you, simply call Formatter.FormatAsync() (or its synchronous brother). You can choose to use the annotation (which I highly recommend because of its ease-of-use) or you can specify the area to format through TextSpan objects (which each node has as a property).


This is one of those helpers that eluded me for a while. So far I have come across two major ways of creating the new syntax tree: either you change the syntax nodes themselves (though technically they return a new node with similar data considering everything is immutable) by calling .Replace*, .Insert* or .Remove* or you use the wonderful DocumentEditor class which takes away a lot of the pain from this process.

Certainly when you have multiple transformations to the document, this comes in really handy. If you’re going to change individual syntax nodes then the benefits don’t seem that big but once you start having more than just that one node then you quickly see lines of code decreasing by 50% or more (and the complexity follows a similar line). Another important note: if you want to change multiple syntax nodes on the same level in the tree (for example: two methods in the same class) then adapting one of them will invalidate’s the other one’s location if you add or remove characters. This will cause problems when you rewrite the tree: if changing method 1 creates a new tree with a few more characters to that method, method 2 will try to replace the tree at the wrong location. This might sound rather vague but if you ever have this problem, you will instantly recognize it. Suffice it to say that DocumentEditor takes care of this for you.


You’ve already seen .WithAdditionalAnnotations() to, well, add additional annotations to your node, token or trivia. Keep an eye on this pattern of .With* extension methods, you might find them to be very useful. Certainly when you’re constructing a new statement/expression/member/whatever which consists of multiple aspects, you’ll find these things. For example as part of my diagnostic that turns a single-line return method in an expression-bodied member (aka: int Method() => 42;) I had to use the existing method and turn it into a new one with this specific syntax. The code for this became very fluent to read through these statements:


This isn’t exactly part of the API but it is so powerful that I can’t omit it. The RoslynQuoter tool developed by Kirill Osenkov is absolutely amazing to work with. If you ever want to know how the tree for a certain snippet of code looks, simply put it in the tool and you get a detailed view of how it’s built up. Without this, I would have many extra hours of work trying to figure out how a tree looks by using the debugger to look at each node’s .Parent property. Luckily, no more!

I hope this helps you get started (or expands your knowledge) of important parts of the Roslyn API. If you’re interested in reading through more complete examples, you can always take a look at VSDiagnostics.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Introducing: VSDiagnostics

I am happy to announce the first release of VSDiagnostics! This project is a group of diagnostics meant for Visual Studio 2015 (and up?) which will help the developer adhere to best practices and avoid common pitfalls.

These are a few examples of the scenarios currently supported:

If statements without braces


String.Empty instead of an empty string


ArgumentException that can use nameof()


A catch clause that catches a NullReferenceException


Throwing an empty ArgumentException


Catching Exception without other catch clauses


And many more!

For the full list, take a look at the Github page. If you have a suggestion in mind or you are interested in contributing, let me know: I want this to be a community powered project. I hope this first release already proves helpful to you and I’m eager to hear your feedback and criticism.

How do I use this?

Simply create a new project using Visual Studio 2015 RC and add the NuGet package! If you don’t find it: make sure you’re also looking in the NuGet V2 package source.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Introducing: RoslynTester

When you create a new solution using the “Diagnostics and Code Fix” template, 3 projects will be created:

  • The portable class library which contains your analyzers and code fix providers,
  • A unit test project
  • A Vsix project to install them as an extension

If you look at the 2nd project you will notice that it creates a few files for you from the get-go: classes like CodeFixVerifier, DiagnosticVerifier, DiagnosticResult, etc.
These classes can be used to unit test your analyzers very easily: you pass in your test scenario as a string, specify the resulting diagnostic you expect, optionally provide a transformed code snippet in case of a code fix and that’s it: you’re done.

I was very pleased by what MS provided but it left me with one annoying problem: that testing code will always stay the same unless I change it myself. Often this is an okay scenario but since Roslyn is under active development and the API can still change (and it does), this prevents me from upgrading. When you look at the version of the Roslyn binaries that are provided with that project template, you will notice that they are from Beta-1. At the time of writing, Roslyn has gone past that to Beta-2, RC1 and eventually RC2. Before I realized this, I took to the Roslyn issue tracker with a few issues that apparently couldn’t be reproduced. It was then that I realized that I might have an outdated installation.

When I upgraded from Beta-1 to RC2 (in intermediate stages) I noticed that some breaking changes were introduced: methods being renamed, types being removed, accessibility restricted, etc. This left me the choice between either diving in that code or sticking to an outdated API (with bugs). The choice wasn’t very hard and I managed to get everything working with the RC2 API. However because of the outdated project template I don’t want to have to manually update those files every time (and I wouldn’t want to force you to do it too either)!

Therefore I present to you: RoslynTester!

This small NuGet package is exactly what you think it is: those few classes cleaned up and put inside a NuGet package. Now I (and you) can simply remove the auto-generated test files and instead simply reference this package to get all the testing capabilities. I will try to keep this up-to-date with the most recent Roslyn NuGet package so none of this should be a problem anymore. If I come across scenarios where I can expand on it, I will do that too of course. In case you are interested in contributing something, feel free to take a look at the Github page!

Sidenote: if the NuGet package doesn’t show up in your NuGet browser, go to your settings and enable the NuGet v2 package feed. I’m still figuring out NuGet and for some reason it only shows up there.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Getting started with your first diagnostic

With the release of Visual Studio 2015 RC, we also received the pretty much final implementation of the Diagnostics implementation. This SDK allows us to create our own diagnostics to help us write proper code that’s being verified against those rules in real-time: you don’t have to perform the verification at a separate build-step. What’s more is that we can combine that with a code fix: a shortcut integrated in Visual Studio that provides us a solution to what we determine to be a problem.

This might sound a little abstract but if you’ve been using Visual Studio (and/or Resharper) then you know what I mean: have you ever written your classname as class rather than Class? This is a violation of the C# naming conventions and visual studio will warn you about it and provide you a quickfix to turn it into a proper capitalized word. This is exactly the behaviour we can create and which is integrated seemlessly in Visual Studio.

I gave this a go exactly 1 year ago but decided against continuing because there wasn’t a final version of it yet and it was really cumbersome to test. That combined with the fact that it was hardly usable (not many people had Visual Studio 2015 yet) made me wait until it had matured and was properly supported. Luckily, it seems that time has finally come.

The setup

In order to get started you need a few things installed:

You will notice that each of these downloads are specific for the RC version, which is what I’m using at the time of writing. Make sure that you don’t mix up CTP-X, RC and RTM versions since that is bound to create issues.

Creating an Analyzer

Even though the official template says “Diagnostic and CodeFix”, the term “Analyzer” is used equally, if not more, as “diagnostic”. I don’t believe there are hard conventions on this yet so use what you feel more natural. I personally prefer to append “Analyzer” to my.. diagnostics.

In Visual Studio, create a new project (and a solution if needed) using the “Diagnostic with Code Fix (NuGet + VSIX)” template, found under “Extensibility”. This immediately indicates a very useful feature: you will be able to distribute your analyzers using NuGet and/or you can choose to distribute them as an installable extension instead. This makes it very easy to deploy in your environment and share it with others should you want to.

Create the project
Create the project

Now on to the real work: we will create an analyzer that shows a warning when we throw an ArgumentException without passing a parameter to it. The use of this is that we will make sure that we’re never just going to throw such an exception without specifying what argument is being annoying in the first place.

After your template is created you will notice 3 projects in the solution: a portable class library which contains your analyzers and code fix providers, a test project and an extension project. You can ignore the latter one and we’ll focus on the first two.

When you look at your analyzer you see an entire example for you to start from. The nature of the diagnostic we will create however is such that we will analyze a syntax node, not a symbol. The code we implement is very straightforward:

I’ve disregarded globalization because it is an extra hurdle to readability and I don’t expect my project to ever become popular enough that it warrants different languages to be supported. Aside from that you’ll notice that I also used a lovely Expression Body for the SupportedDiagnostics method.

The first thing I did was register my analyzer on a a syntax node, a throw statement to be precise. This evidentely means that each time a throw statement is encountered when the tree is walked through, my analyzer will execute.

The actual implementation is very straightforward:

  • Verify the node is a throw statement
  • Verify the expression creates a new object
  • Verify the new object is of type ArgumentException
  • Verify there are no arguments passed to the constructor

And that’s it. If these 4 conditions are true, I believe there to be an empty ArgumentException call and I report a warning on that location.

Testing the analyzer

If you now set the Vsix project as your startup project and press the big green “Start” button, a new Visual Studio instance will be launched. Use it to create a new project and you will notice that your analyzer is included. You can now let yourself loose on all sorts of scenarios involving ArgumentExceptions!

However I wouldn’t be me if I didn’t look into unit testing instead. Luckily, this is very easily done with this release. In fact, it’s so easy that there’s really not much looking into: you create a test class that inherits from CodeFixVerifier, override the GetCSharpDiagnosticAnalyzer and GetCSharpCodeFixProvider as needed, you write source code in plain text and you use the helper functions VerifyCSharpDiagnostic and VerifyCSharpCodeFix to assert whether or not a diagnostic/code fix should occur at the given position. If nothing should occur you just pass in the source code as a string and if you do expect something, you pass in a DiagnosticResult.

In code:

That’s how easy it now is to create your own slim Resharper. Your code is evaluated against your rules as you type, you can write them yourself very easily and you can export them as needed. I will definitely port the few analyzers I created as a test last year and expand it with many others I can think of and I encourage you to do the same (or contribute).

For more information on how to get started with these analyzers I recommend a couple of resources:

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this