C# 6.0

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.