C# 6 Preview: Expression-bodied members

C# 6 is expected to simplify writing properties and methods that involve a single expression. Consider this property exposing a backing field, for instance:

        private string firstName;

        public string FirstName
                return this.firstName;

We may now write this as:

        private string firstName;

        public string FirstName => firstName;

And this is also quite handy for more complex properties:

        public string FullName => string.Format("{0} {1}", this.firstName, this.lastName);

It works pretty nicely with indexers, even though the C# feature descriptions (PDF) document says it shouldn’t work in the current CTP:

    public class Inventory
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item)
            this.inventory[index] = item;

The expression-bodied members feature gives you a pretty convenient way to write getter-only properties. However, this syntax isn’t restricted to properties alone; you can also use it with methods. The following examples are from the official C# feature descriptions (PDF):

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);

public static Complex operator +(Complex a, Complex b) => a.Add(b);

public static implicit operator string(Person p) => p.First + " " + p.Last;

void methods, which don’t return anything, may also take advantage of this syntax. In fact, we can quite easily rewrite the Inventory class’s operations using expression-bodied methods:

    public class Inventory
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item) => this.inventory[index] = item;
        public void RemoveAt(int index) => this.inventory[index] = null;

You can appreciate how this can make classes much more concise.

C# 6 Preview: Parameterless struct Constructors

Update 20th October 2015: As Karl Fenech pointed out, this feature has been dropped in the final version of C# 6.0.

Up until C# 5, you couldn’t have a parameterless constructor in a struct. So if you try something like this:

    public struct Point
        public int x;
        public int y;

        public Point()
            this.x = 0;
            this.y = 0;

        public Point(int x, int y)
            this.x = x;
            this.y = y;

…then it’s not quite going to work:


At the time of writing this article, using a parameterless constructor in a struct as above is now supported, but as an experimental feature. This means you need to edit your project’s .csproj file and add the Experimental language version as shown below:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

Parameterless struct constructors still require you to initialise all members of the struct, just like any other struct constructor.

Additionally, parameterless struct constructors must be public:


The reason for this is explained in the C# Design Notes for Aug 27, 2014:

C#, VB and F# will all call an accessible parameterless constructor if they find one. If there is one, but it is not accessible, C# and VB will backfill default(T) instead. (F# will complain.)

It is problematic to have successful but different behavior of new S() depending on where you are in the code. To minimize this issue, we should make it so that explicit parameterless constructors have to be public. That way, if you want to replace the “default behavior” you do it everywhere.

C# 6 Preview: Exception filters

We already have the ability to branch our exception-handling code depending on the type of exception, by using multiple catch blocks:

                Console.WriteLine("Enter a number");
                string inputStr = Console.ReadLine();
                int input = Convert.ToInt32(inputStr);
                Console.WriteLine(5 / input);
            catch(FormatException ex)
                Console.WriteLine("Input must be a number");
            catch(DivideByZeroException ex)
                Console.WriteLine("Can't divide by zero");
            catch(Exception ex)

In C# 6, we will be able to filter exceptions by handling them only if a condition is true. For example, we may want special treatment for exceptions that have an InnerException:

        static void Main(string[] args)
                throw new InvalidOperationException("Invalid operation",
                    new Exception("Justin Bieber is breathing"));
            catch(Exception ex) if (ex.InnerException != null)
                Console.WriteLine("  -->{0}", ex.InnerException.Message);
            catch(Exception ex)


An additional benefit of exception filters is described in the C# feature descriptions (PDF):

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.

The same PDF also describes a method to take advantage of the conditional expressions used in exception filters in order to perform some action that uses but does not actually handle the exception. The description and code below are taken from that PDF.

It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:

private static bool Log(Exception e) { /* log it */ ; return false; }
try { … } catch (Exception e) if (Log(e)) {}

C# 6 Preview: The Safe Navigation Operator (?.)

The safe navigation operator, first announced and described in this blog post, has been available since the first Visual Studio 14 CTP due to its popularity in Visual Studio User Voice..

The operator, written as ?. in code, has been referred to by many names: safe navigation, null-conditional, null propagation, and conditional access are the ones I’ve come across so far.

Just to demonstrate the concept in an extremely simple manner, consider the following code:

            List<string> list = null;
            int count = list.Count;

It’s pretty obvious that if you try to run the above code, you’re going to get a NullReferenceException, because you’re trying to access the Count property of an object that is null.

Now, the example above can seem dumb because it’s pretty obvious that the list is null, but sometimes objects can come from external sources or user input, and so you have to be careful how you handle them. In this case we can work defensively by adding a null check:

            List<string> list = null;
            if (list != null)
                int count = list.Count;

That’s okay. But it can get pretty messy when there is a chain of references involved. Consider a binary tree, for instance.

var something = binaryTree1.LeftChild.LeftChild.Name;

If we were to write defensive conditionals for this, you effectively need a null check for each access.

            List<string> list = null;
            int? count = list?.Count;

The use of the safe navigation operator involves putting a question mark before the dot operator, as shown above. If list happens to be null (which it is in this case), then the Count property is not accessed, and null is immediately returned. Since list?.Count may return either a number or null, the count variable must now be nullable.

The safe navigation operator pays off pretty nicely when you have more complex reference accesses:

var something = binaryTree1?.LeftChild?.LeftChild?.Name;

It also works pretty nicely with the null-coalescing operator.

            List<string> list = null;
            int count = list?.Count ?? 0;

We can even use it to guard access to array elements when the array is null:

            string[] names = null;
            int length = names?[1].Length ?? 0;

…or guard access to array elements which may themselves be null:

            string[] names = new string[] { "Steve", null, "John" };
            int length = names[1]?.Length ?? 0;

The safe navigation operator is quite convenient in properties which make use of object instances. Consider the following property:

        public string SessionId
                if (this.Session != null)
                    return this.Session.Id;
                    return null;

We can now simplify this to:

        public string SessionId
                return this.Session?.Id;

It’s also convenient to use the safe navigation operator to raise an event only if some delegate is subscribed to it. Consider an INotifyPropertyChanged implementation:

        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(name));

You can’t just stick in a ?. before the paranthesised argument list. So the recommended way to do this is by using the Invoke() method:

        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
            PropertyChangedEventHandler handler = PropertyChanged;

            handler?.Invoke(this, new PropertyChangedEventArgs(name));

The safe navigation operator isn’t going to change our lives. But it’s one of those sweet syntactic sugar features that we’ll grow to love in time.

Coast of Bones


Coast of Bones is the 8th scenario of the human campaign in the Warcraft 2 expansion set, Beyond The Dark Portal. Your objectives are, as is often the case, to destroy all your enemies.


You start off with a small force on a barren piece of land, and you have a few ships that will help you move to another place where resources are hopefully present.


In the screenshot above, you can see the entire map, enabled thanks to the on screen cheat. Your enemies are the white orcs to the west, purple to the southwest, and yellow to the south. The white ones are not very well-defended, allowing you to take over their base, and there is also a spare gold mine on the same piece of land. The purple orcs are better defended, and the yellow orcs are tough and have a strong naval presence.


You have two dwarven demolition squads. You can put them on a transport and use them to take down a couple of cannon towers. The first place to land is shown above.


This will allow you to take down the yellow cannon tower on the island, which is in a strategic location and monitors sea traffic in the area.


Land the second demolition squad on the northwestern landmass.


Then, use it to destroy the white cannon tower that guards the entrance to the white base.


With the cannon tower out of the way, you can now ferry your troops to the white base, and engage the enemy.


After killing the defenders, take down any towers, and then finish off the white orcs by destroying their buildings.


Establish your own base, building a town hall, farms and a lumber mill.


Establish your economy by having peasants mine gold and harvest lumber, and keep building farms to sustain your base’s growth.


Invest in your defences, by manning each entry point to the base and setting up towers to assist them. Continue to grow by building a barracks and upgrading your town hall to a keep.


Build stables to be able to train knights, and build a gnomish inventor to prepare for a naval presence (you will need gnomish flying machines to sniff out enemy giant turtles).


There’s an oil patch to the southwest. It’s pretty close to purple’s base, but is also quite convenient. It’s a good place to start setting up oil operations.


Build a shipyard there, but be prepared to face some heavy resistance from purple and yellow orc ships. One or two well-placed ballistas should keep them at bay (pun not intended).


At this point you will also see more activity from the yellow orcs, who will frequently make landings at the east side of the base. Make sure you are always well-defended.


My first shipyard couldn’t withstand the strength of the enemy naval forces, so I had to build another. I also reinforced my defences with a second ballista, seen on the right in the above screenshot. The ballista is out of range of enemy ships, and they conveniently get stuck trying to attack it.


When the main gold mine runs out of gold, you can build a town hall and start using the second one.


Continue investing in your naval operations by building a second shipyard, a refinery, and a foundry. Make sure you have a steady supply of oil.


Once you have a few battleships, you can begin to attack coastal buildings. Weakening purple’s naval presence is a good start.


When the oil platform runs out of oil, there’s another oil patch to the southeast you can use.


Be careful though – it’s an easy target for purple and yellow orc ships, and also for yellow orc troops.


Continue attacking purple’s coastal area…


…but keep your own operations safe. The central oil platform is an easy target for ships, land troops, and death knights’ whirlwinds.


As the tide of the battle permits, destroy the last remnants of purple’s naval presence.


Continue the attack towards the yellow orcs’ island coast, but be careful – it’s easy for your ships to get trapped in the narrow canals, in which they are easy prey for catapults and whirlwinds.


Make a landing into purple orc territory.


They may be grounded, but they can still put up a fight.


Bring in additional troops if you need.


Put an end to any death knights, because they weaken your forces pretty quickly.


Then work on paralysing their production by destroying strategic buildings, such as the fortress.


In this scenario, orcs usually don’t use air units; but they may do that when they get desperate. Having a couple of archers handy is a good idea.


With most of the purple forces neutralised, send fresh ships into the heart of the yellow orcs’ gulf.


Destroy the naval defences there.


Once the ships are destroyed, focus on destroying coastal buildings to completely annihilate yellow’s naval presence.


You will also find that many other buildings and forces are within reach of your battleships from the gulf, so you can easily bring the yellow orcs to their knees.


Complete the last preparations for an invasion by destroying orc units and buildings along the rest of the coast.


With that done, you can now make a landing on the yellow orcs’ island.


Bring in additional forces as needed.


Destroy strategic buildings first…


…and then finish off the remaining farms.


Enjoy your victory.


"You don't learn to walk by following rules. You learn by doing, and by falling over." — Richard Branson