1. C# 6
One of the popular languages c-sharp has evolved over the years, under the guidance of
Anders_Hejlsberg, into a feature rich language that is used on billions of devices world-wide.
Version 6, is the first to be compiled with Roslyn the new compiler as a service. This is
important because unlike in previous versions, that were compiled with C++.
2. Roslyn is actually part of the .Net ecosystem. This will allow everybody to leverage the
compiler and ensure Microsoft can innovate C# at a faster cadence, while at the same time
ensuring more robust grammar parsing.
Null-conditional operators
This has to be the most important new feature and is designed to strengthen defensive
programming. By simply allowing you to write your code naturally while at the same time
providing null checking.
int? length = (users!= null)?users.Length:null;
This can now be re-written as.
int? length = users?.Length;
As you can imagine if require multiple levels of null checking, the code quickly becomes
unreadable.
string postCode = ((user != null) && (user.Address != null))
3. ? user.Address.PostCode : null;
Is now far more succinct.
string postCode = user?.Address?.PostCode
Additional we can perform a null check against a delegate.
if (OnPropertyChanged != null)
{
OnPropertyChanged(this, value);
}
To this.
OnPropertyChanged?(this, value);
4. Await in catch and finally
The Async operator introduced in C# 5 didn't allow for the await keyword use in catch and finally
blocks. Which only forced the developer to implement workarounds to compensate. Now with C# 6
we have this feature and the last hurdle to Async programming has been removed.
Service service = new Service();
try
{
res = await service.OpenAsync(…); // We only had this.
}
catch(Exception e)
{
await LogService.LogAsync(service, e); // We Now have this.
}
finally
{
if (res != null) await service.CloseAsync(); // … and this.
}
5. nameof
Refactoring is good programming and Visual Studio includes refactoring tools, like renaming,
this works looking at parse the code to look too understand how to update the code. However,
consider the following:
public string SomeMethod(string valueOne, int valueTwo)
{
if (valueOne == null)
{
Throw new ArgumentException("the parameter valueOne of SomeMethod
is null");
}
If we now try to rename the SomeMethod or valueOne, visual studio would simple ignore
the message found in the argument exception, leaving this code stale.
However, with the nameof expression, we can rewrite this code to protect against rename
and event validate against spelling errors.
6. public string SomeMethod(string valueOne, int valueTwo)
{
if (valueOne == null)
{
throw new ArgumentException($"the parameter {nameof(valueOne)}
of {nameof(SomeMethod)} is null");
}
Some tools like Resharper do attempt to fix these issue they are not perfect.
7. String interpolation
String.Format is versatile and is preferable to concatenation, but it is little clunky and error prone. In
particular the placeholders {0} must match the arguments supplied separately or an exception is
thrown:
var s = string.format("{0,20} is {1:D3} years old", user.Name, user.Age);
Now becomes.
var s = $"{user.Name,20} is {user.Age:D3} years old";
Whats more you can also not included method call and and even extensions methods.
var s = $"{user.FullName()} is {DisplayAge(user)}";
This will produced more concise, readable and error less prone code.
8. Auto-Property Initializers
Properties have been in C# since the very beginning with a minor tweak. With version 6 we
can now initialize properties with an expression, so this.
public class Custom
{
public DateTime TimeStamp { get; private set; }
public Address address { get; private set; }
public Customer(string first, string last)
{
TimeStamp = DateTime.UtcNow;
Address = new Address();
Address .AddressLineOne=”197 Home Street”;
Address .PostCode = ”XX1 1SS”;
}
}
9. Becomes this.
public class Customer
{
public DateTime TimeStamp { get; } = DateTime.UtcNow;
public Address address { get; } = new Address {
AddressLineOne=”197 Home Street”,
PostCode = ”XX1 1SS”
};
}
10. using static
Previously if you wanted to access static methods you needed to prefix the contain class
which lead to more verbose code
using System;
class Program
{
static void Main()
{
Console.WriteLine(Math.Sqrt(3*3 + 4*4));
Console.WriteLine(DayOfWeek.Friday - DayOfWeek.Monday);
}
}
11. Now with the static using we can reduce this repetitive code too this.
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
static void Main()
{
WriteLine(Sqrt(3*3 + 4*4));
WriteLine(Friday - Monday);
}
}
Like many of the other feature this improves readability, however the possibility namespace
clashes also increases.
12. Index Collection Initializers
We also have a small improvement to initializers, that allow us to explicitly declare that we're
setting an index, so this.
var numbers = new Dictionary<int, string> {
{7, "seven"},
{9 , "nine"},
{13 , "thirteen"}};
Becomes this.
var dict = new Dictionary<string, string> {
[7] = "seven" ,
[9] = "nine",
[13] = "thirteen" };
13. Now while if example above show that we're actually setting an index property, this feature
really shines with objects rather than values.
var customers = new Dictionary<string, Customer> {
["1"] = new Customer("joe","doe"),
["2"] = new Customer("joe","doe")
};
Under the covers all c# is doing is rewriting use the Add methods.
This boilerplate code while not necessary does increase the readability. I addition, C# will
can now resolve extension methods with will be able to allow any collection utilize Initialize rs.
Conclusion
You could be forgiven for thinking Microsoft is running out of idea's and the new feature are
only boiler plate code and that C# is starting to fossilize. While It's true that as programming
language mature, innovating is harder, as the grammar becomes more complex.
The process of migrating a language compiler onto a new platform is a huge undertaking. So
in future release we can expect more innovation to return. Finally, while these feature could
be described as boilerplate I would counter that this is true for high level languages as they
ultimately compile down to Assembly.