Visual Studio 2015

Crashing Visual Studio 2015 with Explicit Interface Implementations

In F#, all interface implementations are always explicit meaning that the interface methods will only be accessible when treating the implementing type as that interface. This makes sense in F# because it removes all ambiguity around what the method applies to. Explicit implementations also force us into coding to the interface because other miscellaneous members of the implementing type aren’t exposed through the interface definition. For these reasons I’ve been hooked on explicit interface implementation and even use it almost exclusively with great success in my C# applications.

Imagine my surprise then when Visual Studio 2015 crashed when I tried to rename an explicitly implemented interface method! The first time it happened I figured it was probably just Visual Studio misbehaving but when I reopened the solution and tried again the same thing happened! Clearly there was something more to this.

RefactorCrash

Renaming an explicitly implemented interface method causes Visual Studio 2015 to crash.

Hoping that I’d perhaps stumbled upon something that was fixed and included in Update 1, I upgraded Visual Studio and tried again. The crash still occurred.

To narrow down the issue I created a brand new solution with a console application. Within the new project I defined a simple interface with a single method and explicitly implemented it in a class. At this point I attempted to rename the method and it worked as expected. I then tried renaming the interface method directly on the interface and that also worked as expected. Then I figured that it must have something to do with how the interface was being used so I created an instance of the class, converted it to the interface, and tried the rename again and it was successful. Finally, I added a line to invoke the interface method and tried the rename one more time. Oddly, it again worked as expected.

On a whim I decided to move the interface and implementation into a separate project. After adding the project reference and doing a test build I again tried to rename the method and sure enough, Visual Studio crashed. I’ve since played with a few different combinations and have been able to successfully recreate the crash as long as the interface is defined in a separate assembly and I tried renaming the method via the explicit implementation.

In summary, it appears that in order to recreate this crash the following conditions must be met:

  • Interface must be explicitly implemented
  • Interface must be defined in a separate assembly than where it’s used
  • Rename must be attempted against the explicit implementation
  • Interface method must be invoked – simply creating an instance won’t cause the crash.

I’ve submitted the issue to Microsoft on Connect but this seems like such an edge case I’d be surprised to see a fix anytime soon. In the mean time, if this is something you encounter you can safely rename the method on the interface itself or at the call site; neither of those seemed to be an issue.

If you’d like to mess around with this issue on your own, I’ve shared my sample project on GitHub.

Advertisements

C# 6.0 – String Interpolation

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

I really debated about whether I should write about C#’s upcoming string interpolation feature yet. On one hand it’s an interesting feature that I’m looking forward to. On the other hand, it has already been announced that the feature is going to change from its implementation in the current preview. With that in mind I decided that it’s interesting enough to go ahead and write about it using the current syntax but highlight how it will change, much like how it has been done in the feature description document.

When I first heard that string interpolation was coming to C# I immediately experienced flashbacks to the very early days of my career when I was working with some Perl scripts. I really hated working with the language but something that always stuck with me and I missed when jumping to other languages was its string interpolation feature.

At a glance, Perl’s string interpolation feature let us embed variable names inside string literals and the compiler would handle the details of replacing the variable name with the value. My Perl is rusty to say the least but a simple example would essentially look like this:

my $name = "Dave";
print "My name is $name";

Upon execution, the script would write out the following text:

My name is Dave

Side note: I think this is the first time Perl has appeared on this blog. Hopefully it’ll be the last!

Perl’s implementation is more advanced than I’ve shown in this example but it clearly shows the usefulness of the feature. When .NET finally came along and I learned about String.Format I had hopes that it could evolve into something like the Perl feature described above. String.Format is certainly a useful method but it can quickly become a maintenance headache.

Traditional format strings have a number of problems each stemming from the index-based hole approach. First, each value must be supplied in the order that corresponds to the index which isn’t necessarily the order that the values appear in the string. Next, as the number of holes increases, it can be difficult to discern what each hole represents. This isn’t normally a problem for strings with only a few holes but consider the nightmare of keeping indices straight on a format string with more than 50 holes like I once encountered. Finally, String.Format validates only that enough values were supplied to fill each of the holes but if values were provided than there are holes there’s not even a compiler warning. Combine this with one of those 57-hole strings and good luck finding which indices are off or which values should be removed.

C#’s string interpolation aims to fix each of the aforementioned problems. The current implementation uses a slightly clunky version of the traditional format string syntax in that each hole must be prefixed with a backslash. Here’s how the previous example would be written in C# 6.0 using the syntax that’s in the current preview:

var name = "Dave";
WriteLine("My name is \{name}");

Just as in the Perl example, the compiler will resolve the name and fill the hole with the appropriate value. What’s more is that the compiler also verifies that each name exists in the current context and flags anything it can’t resolve as an error.

Per the upcoming features document, this syntax will be changed to something a bit friendlier. Rather than prefixing each hole with a backslash, the string will be identified as an interpolated string by prefixing it with a dollar sign like this:

var name = "Dave";
WriteLine($"My name is {name}");

In this trivial example the net effect on the code is moving and replacing a single character but it’s easy to imagine more complex interpolated strings becoming significantly shorter. (There will also be a FormattedString class added to the System.Runtime.CompilerServices namespace to facilitate custom formatting via the IFormattable interface but I won’t cover that in this article).

That interpolated strings (in either form) closely resemble traditional format strings is not entirely coincidental because ultimately, each interpolated string is syntactic sugar for invoking String.Format. Essentially, the compiler replaces each of the named holes with indexed holes and constructs the value array from the provided names. The benefit of this is that anything you can do with traditional format strings such as including alignment and format specifiers also is also possible with interpolated strings. For instance, we could easily represent a date in ISO 8601 format as follows:

"Current Date and Time (UTC): \{DateTime.UtcNow:o}"

So that’s C#’s string interpolation feature in a nutshell and I’m pretty excited about the direction it’s going because it’ll gradually clean up a lot of code. Since the feature is still under development there’s an active discussion in progress over on the Roslyn site. If you’re interested in seeing some of the thought process behind where this feature is going I encourage you to check it out.

C# 6.0 – nameof Expressions

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

I’ve lost track of the number of times I’ve needed to pass along the name of something be it a property, method, or type. Historically we’ve relied on hard-coded strings to convey this information but as we’re all too well aware, relying on strings in such a manner is just asking for future problems. For a prime example, we need look no further than our old friend INotifyPropertyChanged.

Consider the following Circle class which typifies the basic INotifyPropertyChanged implementation pattern:

public class Circle
  : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  private double _radius;
  public double Radius
  {
    get { return _radius; }
    set
    {
      _radius = value;
      RaisePropertyChanged("Radius");
    }
  }

  private void RaisePropertyChanged(string propertyName)
  {
    if (PropertyChanged == null) return;

    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

Although this class is pretty boilerplate, it highlights the problem well. First, we’ve violated the DRY principle by encoding a member name in a string. Next, we’ve introduced fragility by relying on the string always reflecting the property name exactly; should the property name ever change we need to remember to change the string as well lest we waste some cycles tracking down why an event handler isn’t picking up the property change. What’s worse is that by encoding the name within a string, we get no compile-time support alerting us to the discrepancy.

The story around INotifyPropertyChanged and other similar scenarios has improved over the years as people have come up with some creative solutions. For instance, I’m particularly fond of the expression tree approach because despite its added complexity, it adds the compile-time support lacking in the string-based approach and ties in nicely to Visual Studio’s built-in refactoring capabilities.

.NET 4.5 improved the story a bit more by introducing a few attributes we could apply to optional parameters to get information about the method caller with CallerMemberNameAttribute being the most notable for this discussion. By decorating a parameter with CallerMemberNameAttribute as shown in the revised RaisePropertyChanged method that follows we’re instructing the compiler to inject the name of the member that invoked the method.

private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
  if (PropertyChanged == null) return;

  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

With this revised version, we could simply invoke the method without passing the name and the compiler would resolve the name for us. The problem with this approach is that there’s nothing in IntelliSense to inform us that the parameter is decorated with the attribute and there’s nothing stopping us from providing a value. In fact, the compiler won’t even warn that a name won’t be resolved if we do provide a value. Furthermore, while CallerMemberNameAttribute works nicely for this example, it’s only useful when we need the caller name so it won’t help us if we need the name of anything else such as a parameter name. That’s where the new nameof operator comes in.

C# 6.0’s nameof operator is used to resolve the name of an item at compile-time, essentially inserting the string into the compiled code. What’s really great about it is that it’s simple to use and works on any symbol.

In keeping with the INotifyPropertyChanged example, in C# 6.0 we can add compile-time safety to the original example code simply by replacing:

RaisePropertyChanged("Radius");

with:

RaisePropertyChanged(nameof(Radius));

There are plenty of other places I can see the nameof operator coming in handy. For instance, I often like to use a Guard class to perform a variety of pre-condition checks against method parameter values. Such a class typically looks a bit like this:

public sealed class Guard
{
  private static Lazy<Guard> _against = new Lazy<Guard>();

  public static Guard Against { get { return _against.Value; } }

  public void Null(string arg, object value)
  {
    if (value == null) throw new ArgumentNullException(arg);
  }

  // additional guard methods here
}

I generally create the Guard class as a sealed singleton class rather than as a static class to not only create a more English-like API, but also to allow extension methods in certain scenarios. I also like defining the Guard class methods as a fluent interface but omitted that for brevity.

Given that the Guard class operates off of arguments rather than callers, adding parameters decorated with CallerMemberNameAttribute clearly won’t work in this scenario. Instead we can simply update calls to the various methods to use the nameof operator instead of a hard-coded string and our code will immediately be less fragile.

Fun with Code Diagnostic Analyzers

A few days ago I posted an article detailing how to construct a code diagnostic analyzer and code fix provider to detect if..else statements that simply assign a variable or return a value and replace the statements with a conditional operator. You know, the kind of things that code diagnostic analyzers and code fix providers are intended for. As I was developing those components I got to thinking about what kind of fun I could have while abusing the feature. More specifically, I wondered whether could I construct a code diagnostic analyzer such that it would highlight every line of C# code as a warning and recommend using F# instead.

It turns out, it’s actually really easy. The trick is to register a syntax tree action rather than a syntax node action and always report the diagnostic rule at the tree’s root location. For an extra bit of fun, I also set the diagnostic rule’s help link to fsharp.org so that clicking the link in the error list directs the user to that site.

Here’s the analyzer’s code listing in its entirety:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

namespace UseFSharpAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class UseFSharpAnalyzerAnalyzer : DiagnosticAnalyzer
    {
        internal static DiagnosticDescriptor Rule =
            new DiagnosticDescriptor(
                "UseFSharpAnalyzer",
                "Use F#",
                "You're using C#; Try F# instead!",
                "Language Choice",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                helpLink: "http://fsharp.org");

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxTreeAction(AnalyzeTree);
        }

        private static void AnalyzeTree(SyntaxTreeAnalysisContext context)
        {
            var rootLocation = context.Tree.GetRoot().GetLocation();
            var diag = Diagnostic.Create(Rule, rootLocation);

            context.ReportDiagnostic(diag);
        }
    }
}

When applied to a C# file, the result is as follows:

Use F# Analyzer

This is clearly an example of what not to do with code analyzers but it was fun to put together and see the result nonetheless. If you’ve thought of any other entertaining uses for code analyzers, I’d love to hear about them!

I Can Analyze Code, And So Can You

[12 December 2014 – Update 1] Upon setting up a new VM I realized that I missed a prerequisite when writing this post. The Visual Studio 2015 Preview SDK is also required. This extension includes the VSIX project subtype required by the Diagnostic and Code Fix template used for the example. I’ve included a note about installing the SDK in the prerequisites section below.

[12 December 2014 – Update 2] The github project has moved under the .NET Analyzers organization. This organization is collecting diagnostics, code fixes, and refactorings like to showcase the capabilities of this technology. The project link has been updated accordingly.

Over the past several years, Microsoft has been hard at work on the .NET Compiler Platform (formerly Roslyn). Shipping with Visual Studio 2015 the .NET Compiler Platform includes a complete rewrite of the C# and Visual Basic compilers intended to bring features that developers have come to expect from modern compilers. In addition to the shiny new compilers the .NET Compiler Platform introduces a rich set of APIs that we can harness to build custom code diagnostic analyzers and code fix providers thus allowing us to detect and correct issues in our code.

When trying to decide on a useful demonstration for these features I thought of one of my coding pet peeves: using an if..else statement to conditionally set a variable or return a value. I prefer treating these scenarios as an expression via the conditional (ternary) operator and I often find myself refactoring these patterns in legacy code. It certainly would be nice to automate that process. It turns out that this is exactly the type of task at which diagnostic analyzers and code fix providers excel and we’ll walk through the process of creating such components in this post. (more…)