Saturday, September 26, 2015

Creating a Roslyn code fix for Interpolated Strings in C#

In my previous post I showed a possible pitfall with the new C# string interpolation feature. I also showed how I created a Roslyn code analyzer to find these possible problems. As promised I will now follow up with the code fix provider that will help save you some typing when this analyzer fires a diagnostic message. Along the way I hope to show that creating code fixes is not as complicated as it might look.

So our goal is that if we get a diagnostic warning like



we would like our code fix to replace it with something like:

var today = DateTime.Today;
WriteLine(Invariant($"The date is {today}"));

Because I used the 'Analyser With Code Fix' template when creating the solution, I also got a CodeFixProvider into my solution to start with. This is the class where we will be fixing the code by adding the call to Invariant around the interpolated string.

Thursday, September 3, 2015

C# String Interpolation best practices

In this post I will show you my thoughts on using the new C# string interpolation syntax with regard to formatting. I will try to define a best practice for using this new feature and then show how I created a Roslyn based code analyser that checks for this best practice.

Last week a colleague of mine showed us how he used the new C# String Interpolation feature in his project.

var requestUri = $"api/v1/Colors/{id}/Variants"; 

which is equivalent to

var requestUri = string.Format("api/v1/Colors/{0}/Variants",id);

I responded that I like the new syntax, but the downside is that it uses the CurrentCulture of the executing thread as the FormatProvider. This makes the behaviour of this code dependant on the thread context which may lead to unexpected results.

Reboot

Ok, let's state the Obvious: It has been a long time since I wrote a blog post. I have just finished transferring my old content to my new blog: Frank Bakker talks about software development. This way everything will stay together in a single archive.
I have recently started a new job at Aviva Solutions. At Aviva I will be doing what I love to do most: Help customers solve their complex problems by creating high quality software solutions with a team of highly skilled professionals.
For me this new start is a good opportunity to pick up blogging again. Writing a blog forces me to organize my thoughts about a subject in a way you can understand it. I hope this result in both you and me learning something new.