What’s New in C# 6.0 Inside Visual Studio 2015 Preview

csharp_6_header

I’ve created an up-to-date guide that details the features of the final version of C# 6 here

 

After you install the Visual Studio 2015 Preview, you can begin exploring the new language features found in C# 6.0. While there haven’t been as many changes to the language as in previous versions of C#, there are several features that you should be aware of. In this post, I’ll cover
some of the language enhancements in C# 6.0.

In case you missed it, I also wrote another post on my top 5 features in Visual Studio 2015, as well as several nuggets that I found while exploring the Windows 10 Technical Preview that may be interesting to developers.

Diving In Feet First

Make sure you have downloaded the Visual Studio 2015 Preview, and create a new C# Console Application as shown below. Don’t worry about changing the .NET Framework version number.

Custom Windows Layouts

One thing to note is that by default you will be writing in C# 6.0. If you ever need to change this, simply go to the project properties and click “Build” then “Advanced“. You can change the language version to whatever you want as indicated below.

Custom Windows Layouts

Since we are going to be writing C# 6.0, you can leave this setting at “default” or manually select “C# 6.0” to follow along with this tutorial.

The complete Visual Studio 2015 Console Application including all of the demos shown in this article can be found on Github.

Let’s get started!

Static Using Syntax

In previous versions of C#, we would need to add the proper using statement, such as System.Console, then we could write the following line of code:

Console.WriteLine("Hello TDN!"); 

With C# 6, you can now add the using statement and reference the WriteLine method by itself as shown below:

using System.Console;

namespace TDNCSharpSix
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sample One
            WriteLine("Hello TDN!");
        }
    }
}

Auto-Property Initializers

In the past, we may have created our properties with a get and set and then initialized our constructor with the value that we wanted as shown below.

public class Customer
{
    public Customer()
    {
        customerID = Guid.NewGuid();
    }

    public Guid customerID { get; set; }
}

We can now reduce this code block to one line as shown below. No longer do we need to create a setter or constructor.

public class Customer
{
    public Guid customerID { get; set; } = Guid.NewGuid();
}

Dictionary Initializers

Many C# developers felt the format shown below was confusing for creating dictionaries, mainly because of the use of brackets and quotation marks for the data.

Dictionary<string, string> customerNames = new Dictionary<string, string>()
{
    { "Michael Jordan", "Basketball" },
    { "Peyton Manning", "Football" },
    { "Babe Ruth", "Baseball" }
};

The compiler team decided to change this and make it more readable with the following format. This new format will only save you a few keystrokes, but it is much easier to read in my opinion.

public Dictionary<string, string> customerNames = new Dictionary<string, string>()
{
    ["Michael Jordan"] = "Basketball",
    ["Peyton Manning"] = "Football",
    ["Babe Ruth"] = "Baseball"
};

Exception Filters and Async in a Catch and Finally Block

Exception Filters

Exception filters have been supported in Visual Basic, but are new to the C# compiler. They allow you to specify a condition for a catch block. As shown in the following sample, the last catch statement will fire:

try
{
     throw new Exception("Error");
 }
 catch (Exception ex) if (ex.Message == "ReallyBadError")
 {
     // this one will not execute.
 }
 catch (Exception ex) if (ex.Message == "Error")
 {
     // this one will execute
     WriteLine("This one will execute");
}

Async in a Catch and Finally Block

I think many developers will love this feature because they often need to log exceptions to a file or database without blocking the current thread. Here is an example of how one would work:

public static async void DownloadAsync()
{
     try
     {
         throw new Exception("Error");
     }
     catch
     {
         await Task.Delay(2000);
         WriteLine("Waiting 2 seconds");
     }
     finally
     {
         await Task.Delay(2000);
         WriteLine("Waiting 2 seconds");

      }
}

nameof Expressions

How many times in your code do you retrieve the name of a member of your class? You would typically wrap the field in quotation marks as shown below.

public static void DoSomething(string name)
{
     if (name != null) throw new Exception("name");
}

The main problem with this is that it forces you to put strings in your code to represent the name of a member. In C# 6.0, there is a new operator called nameof that will allow us to refactor our code to remove these string literals. The sample shown below will demonstrate how we could refactor that same method.

public static void DoSomething(string name)
{
     if (name != null) throw new Exception(nameof(name));
}

This results in cleaner code and safety when retrieving member names.

String Interpolation

Prior to C# 6.0, we typically concatenate two or more strings together in one of the following ways:

string firstName = "Michael";
string lastName = "Crump";

WriteLine("Name : " + firstName + " " + lastName);
WriteLine(string.Format("Name : {0} {1}", firstName, lastName));

In C# 6.0, we have a cleaner format as shown in the first WriteLine call, but we can also put expressions directly in the string literal to evaluate an expression as shown below:

string firstName = "Michael";
string lastName = "Crump";
int orderNumber = 250000;

WriteLine("Name : \{firstName} \{lastName}");
WriteLine("Name : \{firstName} \{lastName}\nDiscount :\{orderNumber == 250000 ? " You get 25% off your order!" : ""}");

In this sample, the console will return the following as it evaluated that the orderNumber was equal to 250000 otherwise it would not have printed anything:

Michael Crump
Discount : You get 25% off your order!

In Conclusion

It looks like C# 6.0 is starting to take shape now that the preview has been released. While I touched on several of my favorite language features, I obviously couldn’t include all of them. Also, you should be aware that anything I wrote about is subject to change as we saw several language features removed from the Visual Studio 14 CTP. I would encourage you to keep watch on http://msdn.microsoft.com/ for updated information.

At Telerik, we’ve already been experimenting with the Visual Studio 2015 Preview. You can bet that our controls for web, desktop and mobile applications will be ready to go when this new IDE is released. Feel free to download and explore our ASP.NET, WPF and Windows Universal apps UI suites, as well take a look at the overall collection.

DevCraft

Comments