C# 6.0 is here and will shorten your code
Join the DZone community and get the full member experience.
Join For FreeIn case you haven’t heard the news, the new version of Visual Studio is out: Visual Studio 2015 Preview. You can grab it here. With you’ll get:
- A new version of C# language currently at version 6
- .NET Compiler Platform formerly known as Roslyn: the new compiler for C# and VB.NET which is open source and exposes quite a lot of the underlying infrastructure for the user
- New JIT compiler i.e. RyuJIT which is also open source
- Open source subset of .NET Framework
Small things really. This post will focus on the new features in C# 6 which can both shorten your code and make it more understandable. So let’s begin. In fact, only a couple of new features can be used to addmore code to your existing code base.
Class properties enhancements
Writing immutable classes is relatively hard in C# and a few small additions to the language make things easier. Take a look at the following class:
public class Foo : ViewModelBase { public ObservableCollection<string> Bar { get; set; } public bool Readable {get; private set; } public InitialType Type { get; set; } public string Title { get { return string.Format("Type {0} contains {1} elements", Type, Bar.Count); } } public Foo() { Bar = new ObservableCollection<string>(); Readable = true; InitialType = InitialTypes.Empty; } }
That is a typical class found in MVVM frameworks used in data binding. Nothing out of the ordinary, but we would definitely want to shorten some parts a bit. Here is the C# 6 version of the same code:
public class Foo : ViewModelBase { public ObservableCollection<string> Bar { get; set; } = new ObservableCollection<string>(); public bool Readable { get; } = true; public InitialType Type { get; set; } = InitialTypes.Empty; public string Title => "Type \{InitialType} contains \{Bar.Count} elements"; }
That is quite shorter, and yet is the same code. Let’s take a look at what’s changed. First new addition is the ability to initialize properties when declaring them. This removes the unnecessary code from the constructor and helps when your class has multiple constructors. You initialize the property immediately. Next, you can initialize read only properties both when declared and in the constructor. And now the heavy stuff: string interpolation and expression bodies. Notice how the property lost keywords such as get
,return
and a bunch of punctuation? String interpolation has some advantages over String.Format
: it is impossible to forget a value for a placeholder and it is impossible to mistakenly assign wrong value to a placeholder. These two alone are worth the better syntax.
Parameterless struct constructor
When dealing with structs, one will sooner or later find themselves missing the ability to define the default constructor. Because sometimes some values of a structure should not be default initialized. Structures now can have parameterless constructors, but there is a catch: it is the responsibility of the developer to fully initialize all members of the struct
struct Foo { public int Bar { get; private set; } public int Bar2 { get; private set; } public Foo() { Bar = 1; // will not compile until we initialize Bar2 } }
Finally those pesky class invariants will be no more and structures will have to be well defined.
Dictionary initializers
Initializing collections is easy. Dictionaries on the other hand, not so much. Well, at least in C# 5. Now dictionaries can be initialized with the following syntax:
var dict = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3, [3] = 4, };
Short and sweet. Also, have you noticed that typo at the end. The code will try to add the same key twice, but the last value will be present in the dictionary and no exception will be raised here.
Using static
Another code shortening feature, you can now use static functions declared inside static classes without specifying full name. This gives us global functions for the first time in the language, an omission we surely regretted. Here is a small example:
using System.Math; var result = Cos(alpha) * Sin(alpha);
Using await in catch/finally
The last language version brought us the best feature ever: async
/await
which rewrote the code using asynchronous functions into a state machine. However, it was impossible to use it inside catch
block which forced us to work around it. But now it is possible to use it and the following code is history:
WebException e = null; try { // we have a WebRequest here var response = await request.GetResponseStreamAsync(); // ... } catch (WebException ex) { e = ex; } if (e != null) { var response = await ((HttpWebResponse)ex.Response).GetResponseStreamAsync() }
WebException
can now be handled inside the catch
block.
NameOf
When C# 5 was released, we got CallerMemberName
which helped us retrieve the name of a property or a function, but now we can do even more with the built in “symbol stringifier”.
Observe:
public class Foo { public int Property { get { return Get(nameof(Property)); } } }
This will come in handy in MVVM frameworks where knowing the name of the property at compile time can speed things up.
Null propagation operator
While we are in our code-shortening mood, let’s eliminate all those null checks we don’t care about and write something like this:
var result = User?.Addresses?[0]?.City?.State ?? "unknown";
Oh and we can invoke events too:
PropertyChanged?.Invoke(this, eventArgs);
Without even seeing the equivalent code with null checks, this is obviously shorter.
Exception filters
The final feature discussed here are exception filters. For the first time it is possible to decide whether or not to enter a particular catch
block.
Somewhat convoluted example follows:
try {} catch (WebException ex) if (ex?.Response ?.As<HttpWebResponse> ?.StatusCode == HttpStatusCode.NotFound) { /* ... */ } catch (WebException ex) { /* ... */ }
The As
method is simply as
operator invoked as a function which allows better chaining.
If the filter function returns true, the catch
block will be entered, otherwise the next catch
block will be inspected.
vNext
This concludes our tour of the new C# language features introduced in the latest Visual Studio. Few features were dropped, some are on the horizon, some are not yet possible to do easily (I am looking at you non-nullable references).
The list of new and upcoming language features for both C# and Visual Basic.NET can be found here. Keep an eye out for some new and exciting features coming in the future. You can even try implementing some of them yourself.
Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
-
Integrating AWS With Salesforce Using Terraform
-
Front-End: Cache Strategies You Should Know
-
Manifold vs. Lombok: Enhancing Java With Property Support
Comments