Roslyn and the future of .NET languages – Language Features

Boston Code Camp 22 materials: Slides | Language Features Demo Code | Post on Extensions

The new Visual Studio 2015 Roslyn language features include a grab bag of nice changes to help make code more compact and readable. This isn’t an exhaustive list but some of my favorites.

Getter only and initialized auto-properties

public string Name { get; } = "John";

This is a much simplified way to create readonly properties, which previously required a full property with a backing field declared as readonly. This is not the same as an auto-prop with a private setter, which is still a mutable value. The value can be set from a constructor or in line since auto-properties can also now be initialized directly.

Null conditional operator ?.

NameSize = Name?.Length.ToString() ?? "0";

This is going to be great for cutting down on surprise NullReferenceExceptions and is so much more compact than a string of if statement checks.

Interpolated Strings

Console.WriteLine($"User name is {Name}");

Finally, the functionality of String.Format has some readable syntax! In the current VS Preview the syntax uses "\{Expression}" but this will change to use the $ syntax before release.

Expression bodied members (C# only)

public int CountMultiple(int multiplier) => Count * multiplier;

This is mostly just cutting down on space required for these declarations.

await in catch and finally blocks (C# only)

try
{
    await operation.DoWork();
}
catch
{
    await operation.Rollback();
}
finally
{
    await operation.Close();
}

One of those seemingly simple things that could stop you in your tracks if you were in a situation that needed it in C# 5 and needed a lot of extra code to work around.

Read-write properties to implement Read-only interface properties (new in VB)

Public Interface IHaveData
    ReadOnly Property Name As String
End Interface

Public Class ClassDemo
    Implements IHaveData
    Public Property Name
        Get
            Return ""
        End Get
        Set(value)

        End Set
    End Property
End Class

Another one that’s so simple but could really get in the way when it wasn’t available.

 

Download the Visual Studio 2015 Preview: http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs

Check out the full list of new language features and latest updates (and the source code!) on CodePlex: http://roslyn.codeplex.com/wikipage?title=Language%20feature%20status&referringTitle=Home

Read More

Roslyn and the future of .NET languages – Extensions

Boston Code Camp 22 materials: Slides | Extension Demo Code | Post on Language Features

With the new code editors in Visual Studio 2015 now written around the Roslyn compiler a whole new level of extensibility is available both for built in features and user created extensions. If you’ve worked with Visual Studio extensibility before a Roslyn extension can a big improvement both in ease of coding and end user experience.

New Refactorings

Refactoring support was added in Visual Studio 2005 and since then a grand total of 0 new ones have been added. Now two new ones have been added to allow introducing new variables and for inlining existing ones. The experience is much improved for all the existing refactorings too.

New Refactoring Experience in 2015

Diagnostics and Code Fixes

Normal compiler errors show up in the editor as you type but can also be augmented with additional diagnostic checks performed by other Roslyn extensions. One key example is a large portion of the existing FxCop Code Analysis rules which were previously run as an additional build step but now happen on the fly as you type, making it much easier to apply these rules right away and keep your code cleaner from the start.

Unlike with normal compiler warnings or errors that you would normally get with FxCop, many of the new diagnostics include an additional component to actually correct the problem for you when possible, even showing a preview of the changes right in line (just like Refactorings).

Write your own!

Visual Studio has been extensible for a long time but there have been major limitations on how deep an extension could get into the code without writing your own compiler. In 2015, a Roslyn extension can take advantage of deep knowledge of the code in real time through the compiler as a service. Project templates are available that make it easy to set up either a Refactoring or a Diagnostic with (or without) a Code Fix. Deployment can be done either through a VSIX that can go up on Visual Studio Gallery, or now as part of a NuGet package that can be deployed on a project by project basis. The possibilities are endless and I expect a huge flood of Roslyn extensions are going to be available on top of what’s already been added into the product.

 

Download Visual Studio 2015 Preview and the SDK: http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs

Roslyn templates Visual Studio extension: https://visualstudiogallery.msdn.microsoft.com/849f3ab1-05cf-4682-b4af-ef995e2aa1a5

Bill Wagner announcing a new central location for community Roslyn extensions: http://thebillwagner.com/blog/announcing-dotnetanalyzers-diagnostics-and-code-fix-open-source-projects

Read More

Optimizing INotifyPropertyChanged for performance vs convenience

One of the central aspects of implementing the MVVM pattern is the ubiquitous invocations of INotifyPropertyChanged.PropertyChanged in property setters. The simplest version that is commonly seen just passes the property name as a string and builds an EventArgs object in the shared NotifyPropertyChanged method.

public int MyProperty
{
	get { return _myProperty; }
	set
	{
		if (_myProperty == value)
			return;
		_myProperty = value;
		NotifyPropertyChanged("MyProperty");
	}
}

Over time, the verbosity of the basic pattern boilerplate has been reduced in various ways, usually with one of two goals: shorter code or stronger links between the event args and the name of the property itself. One nice technique takes advantage of expressions to create a compile time check on the argument’s match to the a valid property name.

public int MyProperty
{
	get { return _myProperty; }
	set
	{
		if (_myProperty == value)
			return;
		_myProperty = value;
		NotifyPropertyChanged(() => MyProperty);
	}
}

One of the best techniques to emerge so far came about with the release of .NET 4.5 and C# 5 which added the CallerMemberName attribute to automatically resolve the name of the calling property. This provides even easier code and a dead simple implementation in the calling method as well, but does lose out on the ability to make compiler checked calls from outside of the property itself where the property name still must be passed as a string.

public int MyProperty
{
	get { return _myProperty; }
	set
	{
		if (_myProperty == value)
			return;
		_myProperty = value;
		NotifyPropertyChanged();
	}
}

On the other end of the spectrum, pulling all of the responsibility for constructing event args up to the property requires a lot of extra code but can also allow for skipping the allocation of a new PropertyChangedEventArgs object for each call.

static readonly PropertyChangedEventArgs MyPropertyArgs = new PropertyChangedEventArgs("MyProperty");
public int MyProperty
{
	get { return _myProperty; }
	set
	{
		if (_myProperty == value)
			return;
		_myProperty = value;
		NotifyPropertyChanged(MyPropertyArgs);
	}
}

 

It’s great to have all of these options for structuring your code, but how do these all affect performance when lots of data is changing at once? To do some analysis I set up a ViewModel which used each of these variations and ran large timed batches of property changes to get some comparison times. I used each of the four patterns above, with an additional variation on the statically declared PropertyChangedEventArgs which takes advantage of the new nameof operator in C# 6 (VS 2015) to provide compile time checking of the property name.

Explicit String

CallerMemberName

Expression

Static EventArgs

Static EventArgs with nameof

Avg (ms)

10.31

10.63

215.89

9.45

9.65

Median (ms)

10.18

10.35

213.30

9.33

9.43

A few things become clear from this:

  1. The expression method, while providing compile time safety for .NET 4.0 and earlier, is slower to such a degree that it probably shouldn’t be used in any sort of data-intensive UI or in any .NET 4.5+ situation.
  2. The corresponding compiler checked versions of the both of the string based approaches turn out to be a little slower but not enough that it should be noticeable in any but the most performance sensitive scenarios. The added safety of the checks (provided you’re using a new enough language version) should be worth the small cost.
  3. Avoiding repeated allocations of PropertyChangedEventArgs is definitely the fastest method, but based on CPU time probably not a significant enough improvement in most cases to justify the large amount of extra code needed for each property. It is possible that taking memory usage and garbage collection impact into account might provide a more decisive advantage but overall the memory impact of the tiny PropertyChangedEventArgs is likely to be dwarfed in most cases by that of corresponding UIElement objects which are receiving the notifications.

CallerMemberName is probably the best compromise most of the time since it gives up very little in terms of performance but makes for the cleanest code, at least until hopefully some form of automatic notifications on auto-properties can be baked into some future version of C#.

For details of the implementations of each strategy download the test code: Example Implementations

Read More

Digesting the flood of announcements from Visual Studio Connect()

Day 1 of the Visual Studio Connect() event today was packed with announcements, some of which are pretty dramatic changes to the Microsoft development landscape.

The obvious headline announcement which everyone is talking about (and will likely continue to) is the Open Sourcing and Mac/Linux support for the .NET Core Framework. This, along with the NuGet deployment mechanism for app-local copies of the framework, are going to be a huge shift in how .NET apps are developed, deployed, and run on the server. News and commentary is all over the web but Scott Gu’s blog post is a good place to start.

Probably my favorite news of the day was WPF finally emerging from hibernation. The platform is moving forward with fixes to reported issues and general improvements to the platform. Even more exciting, the tooling is getting some long needed attention: visual tree debugging a la Snoop, performance analysis tools, a full refresh of Blend, and a commitment to keep moving the tooling forward for all of the XAML platforms. Read the full roadmap blog post for all the details.

Some of the other under-the-radar announcements came on the Visual Studio side. The integration of MS Research’s Pex project as the new Smart Unit Tests feature should be an interesting addition and is a feature I expect to grow over time into a really powerful code validation tool. Although Roslyn has been out in the wild in CTP form for a while now, the IDE features around it are really starting to come together in the newly released 2015 Preview. Already in this preview a lot of CodeRush/Resharper-like features have been added and the extensibility model is so much better than it has been in the past that I expect community contributions of new code validation and refactoring features to explode over the next few months. My biggest concern at this point is actually around how to manage large sets of these extensions as I don’t think it would be out of the question to end up installing 100+ on top of the built in functionality. Check out details on what’s in the preview and go try it out!

Read More