C# Corner

C# 6.0 Gets More Concise with Expression Bodied Properties, Dictionary initializer

Eric Vogel goes over a few C# 6.0 language improvements that will help make your coding experiences more concise.

C# 6.0 is slated for official release with Visual Studio 2015 later this year. As of now the first release candidate version is available at https://www.visualstudio.com/downloads/visual-studio-2015-downloads-vs.aspx. The sixth iteration of C# brings many small improvements to the language syntax that when combined will make your code more concise and easier to read. Today I'll be covering a handful of these improvements such as expression bodied properties and functions, using static directive, string interpolation, and the new dictionary initializer syntax.

First let's take a look at expression bodied properties and functions. An expression bodied property is declared as a lambda expression.

For example let's say I have a Car class that has Make, Model, and Year properties. I can then declare an expression bodied property named Description that includes each property nicely formatted using an expression bodied property with string interpolation:

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }

    public int Year { get; set; }

    public string Description => $"{Year} {Make} {Model}";
}

Prior to C# 6, the Description property would be declared as:

public string Description { get { return string.Format("{0} {1} {2}", Year, Make, Model); } }

You can see how the new syntax is both more concise and readable than the old property declaration.

Similarly functions can also be declared as expression bodies:

public override string ToString() => $"{Year}-{Make}-{Model}";

You can see how string interpolation makes formatted strings much more readable. You can also use string interpolation on object instances:

Car myCar = new Car { Year = 2015, Make = "ACME", Model = "Roadster" };
Console.WriteLine($"My car is a {myCar.Description}");

Furthermore we can clean up the call to Console.WriteLine to only be WriteLine by utilizing the using static directive on System.Console:

using static System.Console;

Then you can call WriteLine as if it were declared as a local class function:

WriteLine($"My car is a {myCar.Description}");

Now let's take a look at the new Dictionary initializer. Prior to C# 6 you can declare an initialized Dictionary like this:

var items = new Dictionary<string, int> { { "Book", 2 }, { "Blu Ray Player", 1 } };

In C# 6 you can use the new [] initializer syntax as follows:

var moreItems = new Dictionary<string, int>
{
    ["Book"] = 2,
    ["Blu Ray Player"] = 1
};

You can see how the new Dictionary initializer syntax is closer to how you would access the items in the dictionary after it is cleared, thus making it easier to read.

You can see how the new language features are subtle improvements that, when combined, will help make your code easier to maintain and read. Also see Peter Vogel's articles on some of the other new features in C# 6, such as the nameof operator and the null check initializer.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube