Visual Studio

C# 6.0 – Declaration 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!

[Update: 1 Oct 2014] It has been said that if something sounds too good to be true, it probably is. The adage apparently even applies to the proposed C# 6 features that I was excited about. I’m sad to say that it was announced today that declaration expressions would not be part of C# 6.

The C# 6.0 feature I’m probably the most excited about is declaration expressions. That the feature is listed as done on the language feature implementation status page and is included in the CTP only enhances my excitement.

Declaration expressions allow us to define local variables within an expression and scope them to the nearest block. As the CTP C# Features notes, this is particularly useful in conjunction with out parameters. Consider the traditional approach for working with an out parameter:

int result;
var myInt =
  int.TryParse("42", out result)
    ? result
    : 0;

I (like many others) hate this pattern, especially after having been so spoiled with F#’s approach of wrapping the call and returning both the status and parsed value as a tuple. Since C# probably won’t include usable Tuples anytime soon, declaration expressions provide a nice alternative as shown here:

var myInt =
  int.TryParse("42", out var result)
    ? result
    : 0;

In the previous snippet, we’ve moved the declaration of result into the TryParse call itself! Because I opted to use the conditional operator here, result is still visible within the parent context but other constructs (such as if statements) can limit the scope thus decreasing the risk of dealing with an uninitialized value. I call that a win.

Declaration expressions open up all sorts of other possibilities, too. For instance, the CTP notes show how they can improve the developer experience in cases where expressions are required using query expressions as an example:

var myInts =
  from ps in
    (from s in strings
     select (int.TryParse(s, out var result) ? result : (int?)null))
  where ps.HasValue
  select ps.Value;

Without declaration expressions, the preceding query expression would have required us to wrap the parsing logic within another function but because we can include the result variable definition inline, such a query is possible.

Finally, how many times have you written something like this?

var myStr = myObj as MyType;
if (myStr != null)
{
  ...
}

The as operator pattern doesn’t bother me nearly as much as the out parameter pattern but it still feels dirty since it exposes the variable outside of where it’s actually needed. Declaration expressions let us make this a bit prettier, again by moving the declaration inline with the if statement as follows:

if ((var myStr = myObj as string) != null)
{
  ...
}

I like this approach a bit better than the traditional approach not because it lets us write less code (it doesn’t, really since the lines are just merged) but because it limits the scope of myStr.

So yeah, I’m pretty excited about this feature and think it’s safe to assume that I’ll be adopting it just as quickly as I do primary constructors once it’s generally available.

C# 6.0 – Index Initializers

[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!

After two posts of new C# features that I like I thought it would be fun to change the pace a bit and discuss one that my initial impressions leave me questioning its usefulness: index initializers. I think the reason I’m confused about this feature is that all of the examples I’ve seen around it show dictionary initialization like this:

var numbers =
    new Dictionary<int, string>
    {
        [7] = "seven",
        [9] = "nine",
        [13] = "thirteen"
    };

My problem with this is that C# has allowed initializing dictionaries using a very similar manner since version 3! Here’s the same dictionary initialized with the more traditional object initializer syntax:

var numbers =
    new Dictionary<int, string>
    {
        { 7, "seven" },
        { 9, "nine" },
        { 13, "thirteen" }
    };

So we’ve swapped pairs of curly braces for pairs of square brackets and some commas with assignments? I just don’t see the benefit. It’s not that I’m opposed to index initializers; I’m confused as to why another syntax is needed for something we’ve been able to do in almost exactly the same way for years. The hint that may clear up the reasoning comes from the CTP notes which state:

We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

Given that statement, I can see indexer initializers being more useful in conjunction with custom types. Even still, it seems like the only benefit would really be foregoing specific Add method overloads on the custom type but index initializers would still be at the mercy of said type having a compatible indexer property. Unfortunately index initializers aren’t available in the CTP so I can’t really experiment with them at this time and anything else I could say about the feature would be pure speculation.

C# 6.0 – Using Static

[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!

In this installment of my ongoing series covering likely C# 6 language features I’ll be covering one of the features listed as “Done” on the Language feature implementation status page: using static. The idea behind using static is to allow importing members from static classes thus removing the requirement to qualify every member of an imported class with its owner. For the F#ers reading this, using static brings open module to C#.

Consider a method that writes some text to the console:

public void DoSomething()
{
  Console.WriteLine("Line 1");
  Console.WriteLine("Line 2");
  Console.WriteLine("Line 3");
}

In this example, we’ve had to specify the Console class three times. The using static feature we can simply invoke the WriteLine method:

using System.Console;

public void DoSomething()
{
  WriteLine("Line 1");
  WriteLine("Line 2");
  WriteLine("Line 3");
}

The primary benefit in this contrived example is eliminating redundancy but consider a more practical example which makes use of some of System.Math’s members:

class Circle(int radius)
{
  public int Radius { get; } = radius;

  public double GetArea()
  {
    return Math.PI * Math.Pow(Radius, 2);
  }
}

Here we’ve had to qualify both PI and Pow with the Math class. Granted, it only appears twice when calculating the area of a circle but it’s easy to imagine the amount of noise it would generate in more complex computations. In these cases, using static is less about eliminating redundancy and more about letting you stay focused on the problem as you can see in this revised example:

using System.Math;

class Circle(int radius)
{
  public int Radius { get; } = radius;

  public double GetArea()
  {
    return PI * Pow(Radius, 2);
  }
}

With both references to the Math class removed from the GetArea function, its much more readable.

I have to admit that I’m pretty excited about this feature. I can see it going a long way toward making code more maintainable.

C# 6.0 – Primary Constructors and Auto-Implemented Property Initializers

[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!

[Update: 1 Oct 2014] It has been said that if something sounds too good to be true, it probably is. The adage apparently even applies to the proposed C# 6 features that I was excited about. I’m sad to say that it was announced today that primary constructors would not be part of C# 6. It also sounds like there will be some changes around readonly auto-implemented properties.

As much as I prefer working in F#, I can’t ignore the fact that most of my work is still in C#. With Visual Studio “14” now in CTP 2 with some of the C# 6.0 features, it makes sense to take a more serious look at what’s in the works or has already been implemented. As such, I’ll be spending the next few articles describing some of these features and capturing my initial thoughts about them. In this article I’ll cover auto-implemented property initializers and primary constructors. Although these are separate features I suspect they’ll often be used together so it seems appropriate to discuss them at the same time. As with any CTP, everything I examine here is definitely subject to change but information regarding language feature implementation status can be found on the Roslyn Codeplex page.

Anyone familiar with F# should immediately recognize both of these features because they’ve been available in F# for years. I think both of these features are a nice addition to C# because they have the potential to greatly reduce the language’s verbosity and bring some feature parity with F# but I still like F#’s approach better.

Auto-Implemented Property Initializers

Auto-implemented property are being enhanced in two ways: they can be initialized inline, and you can define them without a setter. With inline initialization we can provide an initial value for the auto-implemented property without having to manually set the property via a constructor. For instance, if we have a Circle class with an auto-implemented Radius property we could initialize it as follows:

public class Circle
{
    public int Radius { get; set; } = 0;
}

What’s nice about the initializer syntax is that it sets the generated backing field rather than explicitly invoking the setter through a constructor or other mechanism. This feature also allows us to define a getter-only auto-implemented property, like this:

public class Circle
{
    public int Radius { get; } = 0;
}

As much as I appreciate these enhancements and will happily embrace them when they’re available, it bugs me that the type is still required in the property definition. It would be really nice to have the C# compiler infer the type from the initializer like F# does but for now, this is a nice start.

Primary Constructors

Primary constructors provide a mechanism by which a class (or struct) can accept parameters without a formal constructor declaration by including them in the class definition. The values defined in the primary constructor are scoped to the class but their lifetime is limited to class initialization by default. This makes them perfect for setting fields or initializing auto-implemented properties. Here we include a primary constructor for the Circle class and use it to initialize the Radius property:

public class Circle(int radius)
{
    public int Radius { get; } = radius;
}

The scoping rules for the values identified in the primary constructor are one place that C#’s primary constructors differ from F#’s (yes, I prefer F#’s approach here, too). As I previously mentioned, by default the primary constructor values are available only during class initialization. This means that while you’re free to use them for initialization, you can’t reference them in any methods. For instance, if we wanted to include a GetArea method our Circle class, the following approach would be invalid:

public class Circle(int radius)
{
    public int Radius { get; } = radius;

    public double GetArea()
    {
        return Math.PI * Math.Pow(radius, 2);
    }
}

It would be really nice if we could include an access modifier or attribute instructing the compiler to automatically generate a field but for now, it looks like we’ll have to make due with initialization scoping.

For cases where you need to do more than some basic initialization (such as parameter validation), it’s possible to define a primary constructor body by wrapping the statements in a pair of curly braces (of course, more braces) within the type definition.

As with the auto-implemented property initializers, I really appreciate this feature but wish it would go a bit further. Generally speaking, though, I see this as a positive feature for the language.

Visual Studio: Platform Based References

I’ve been needing to jump back and forth between 32 and 64 bit builds recently. Unfortunately a few of the 3rd party assemblies my project is using are platform specific so I found myself having to manually swap out the references to prevent BadImageFormatExceptions from popping up.  Since Visual Studio doesn’t provide mechanism for this I started exploring external ways to get the right assembly.

On a previous project we where we had this problem we were building with NAnt. With this configuration it was somewhat straightforward to create a dependencies folder that held and organized the different assembly versions and prior to the build, copy the appropriate ones to a folder referenced by the projects. This ensured that we always built the project with the correct assemblies for the target platform.  On this project though, I’m not using NAnt, I’m using MSBuild and I didn’t want to do a custom build task so I looked for another solution.

A 2 year old post from ryangerard.net provided the answer I was looking for.  The solution involves a simple project file “hack” where under each property group we define a variable whose value is the path to the appropriate assembly.

Note: The element name you use should be meaningful to your project. I’ve used ThirdPartyAssemblyPath for illustration purposes.

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
  <!-- snipped -->
  <ThirdPartyAssemblyPath>(path to 32-bit assembly)</ThirdPartyAssemblyPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
  <!-- snipped -->
  <ThirdPartyAssemblyPath>(path to 64-bit assembly)</ThirdPartyAssemblyPath>
</PropertyGroup>

We also need to update the actual reference element to use a hint path based on the variable the variable.

<Reference Include="">
  <HintPath>$(ThirdPartyAssemblyPath)</HintPath>
</Reference>

I was able to leverage a single variable for multiple references because I’m using several assemblies from the same vendor. Since they’re pretty well organized in the vendor’s installation folder I only had to define a single variable for the folder and left the .dll names in the reference definitions.

Once you’ve made these edits you can freely switch between target platforms. I’m not sure how sustainable this is in the long term or on larger projects but it’s definitely an option. Just be careful if you ever need to change that reference that you update the variables rather than the reference or you’ll find yourself right back where you started.

VS2010: Web Standards Update and the CSS Editor

I’ve been doing a bit of Web UI work recently and everything was going fairly smooth until yesterday when I tried opening one of my CSS files in Visual Studio and was promptly greeted with a dialog reading “The operation could not be completed. Unspecified error” and the editor never opened.  A little hunting for the error message and “CSS editor” revealed that the Web Standards Update for Microsoft Visual Studio 2010 SP1 was likely to be the culprit and uninstalling should resolve the issue.

I closed Visual Studio, uninstalled the update, and sure enough, when I reopened my project the CSS file opened just fine. I haven’t reinstalled the update yet. Maybe I’ll try again soon but it seems from the comments on the component’s page that this is a common issue.

More information:

Nesting Files in Visual Studio

A neat trick that I’ve used a few times to help organize files in a project is nest some under a related “master” file just like an aspx file and its code-behind.  I’ve mostly done this to group some page-specific JavaScript files with the page but also to group some partial classes for a WCF service together under a single “master” file.  This is hardly new (I think I did it for the first time with a project file from VS2008 and I know it has been around even longer than that) but every once in a while it comes up in a conversation so I thought it was worth sharing.
(more…)

Operation could destabilize the runtime

Today I was trying to run the code for a project I’ve just been assigned to.  I’d brought down the code from SVN, built the common libraries, and punched F5.  Build succeeded.  Before long the browser loaded and the beautiful new UI stared back and virtually begged me to start clicking around.  Before I could do anything though Visual Studio rudely interrupted with an unhandled exception dialog.  This one looked nasty, particularly since I’d never seen it before: System.Security.VerificationException – Operation could destabilize the runtime…

I found a Stack Overflow question about this that pointed to Json.NET as a possible culprit.  Sure enough, the source of the exception was Newtonsoft.Json.  It seems that Visual Studio Ultimate’s IntelliTrace didn’t like something Json.NET was doing and would throw that exception.  The issue is said to be resolved as of release 6 but I haven’t upgraded the assembly yet.

For the time being I’ve added a rule to exclude *Newtonsoft.* from the IntelliTrace modules list as recommended by in the Stack Overflow answer.  Since excluding the assembly I haven’t seen the problem again.

VS2010: Box Selections

When I first saw the box selection capabilities in Visual Studio 2010 I thought “that’s kind of neat but I’ll probably never use it” and promptly moved on.  I couldn’t have been more mistaken.  In fact, nearly two years later, box selection has become one of those features that I use almost daily.  What surprises me now though is how many developers I run into that still don’t know about them.

Box selections let us quickly make the same change to multiple lines simultaneously.  Creating them is easy – just hold shift+alt and use the arrow keys or hold the alt key while left drag the mouse to define a rectangle.  If you just want to insert the same text onto multiple lines you can define a zero-length box by expanding the box vertically in either direction.

Non-virtual Properties

So what makes box selections so useful?  Some of the things I find them most useful for are changing modifiers and making local variables implicitly typed.  To illustrate, let’s take a look at a few non-virtual properties that we’d like to make virtual.

Zero-Length Selection

Making these properties virtual without a box selection certainly isn’t difficult but it’s definitely tedious.  A box selection lets us make them all virtual at the same time so we can get on with the task at hand.  The thin blue line immediately following the public modifier on each property identifies the zero-length box that serves as the point where we’ll insert in the virtual modifier.

Virtual PropertiesTo insert the virtual modifier we just need to type (or paste) “virtual.”  Here you can see that each property is now virtual and the zero-length box has moved to the end of the inserted text.  What if we decide later though that these properties shouldn’t be virtual after all?

Box SelectionWe can use box selections to remove the virtual modifier from each property just as easily.  In the example to the left we see a box selection highlighting the virtual modifier on each line.  Non-virtual Properties 2To remove the text we can simply delete it.  This will leave us with a zero-length box where the virtual modifiers used to be.  We can then simply click or arrow away to clear the box selection.

Box selections can go a long way toward increasing your productivity by reducing some of the more tedious aspects of programming.  The few seconds they save here and there can really add up over the course of a day.  More importantly though, that time can be spent on the real problems we’re trying to solve.

Further Reading

How to: Select and Change Text

My Standard .hgignore File

Since I started using Mercurial a few months ago I’ve fallen in love with it.  There was a bit of a learning curve for getting up and running but I found that the Tortoise tools are really intuitive and eliminated some of the pain.  Most importantly though, Mercurial addresses the single biggest problem I had when working away from home – no repository access.

(more…)