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
        {
            get
            {
                if (this.Session != null)
                    return this.Session.Id;
                else
                    return null;
            }
        }

We can now simplify this to:

        public string SessionId
        {
            get
            {
                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

screen002

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.

screen003

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.

screen004

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.

screen005

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.

screen006

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.

screen007

Land the second demolition squad on the northwestern landmass.

screen008

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

screen009

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

screen010

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

screen011

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

screen012

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

screen013

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.

screen015

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).

screen016

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.

screen017

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).

screen018

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.

screen019

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.

screen020

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

screen021

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.

screen022

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

screen023

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

screen024

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

screen025

Continue attacking purple’s coastal area…

screen026

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

screen027

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

screen028

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.

screen029

Make a landing into purple orc territory.

screen030

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

screen031

Bring in additional troops if you need.

screen032

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

screen033

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

screen034

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.

screen035

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

screen036

Destroy the naval defences there.

screen037

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

screen038

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.

screen039

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

screen040

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

screen041

Bring in additional forces as needed.

screen042

Destroy strategic buildings first…

screen043

…and then finish off the remaining farms.

screen044

Enjoy your victory.

screen045

C# 6 Preview: Autoproperty enhancements

C# 6 extends the power of autoproperties.

Up to now, if you wanted to have a read-only property, then you had two options. You could either give up on autoproperties altogether, and use a readonly backing field exposed by a property:

        private readonly string name = "Snoop";

        public string Name
        {
            get
            {
                return name;
            }
        }

Or you could use an autoproperty with a private setter, which isn’t really read-only (it could be modified somewhere in the same class), and also means you’ll have to set the value in a constructor:

        public string Name { get; private set; }

        public Dogg()
        {
            this.Name = "Snoop";
        }

Fear not! C# 6 supports autoproperty initializers…

        public string Location { get; set; } = "NYC";

…which, quite conveniently, also work for getter-only properties:

        public string Name { get; } = "Snoop";

So it is now possible to declare an autoproperty without a setter, and its backing field will be implicitly declared as readonly.

These autoproperty initializers would have worked pretty nicely with a feature called primary constructors. But since this feature has been dropped, the usefulness of getter-only autoproperty initializers is restricted to readonly properties.

It is also worth mentioning this note about mutability from the C# feature descriptions [PDF]:

“This is about expressing types more concisely, but note that it also removes an important difference in the language between mutable and immutable types: auto-properties were a shorthand available only if you were willing to make your class mutable, and so the temptation to default to that was great. Now, with getter-only auto-properties, the playing field has been leveled between mutable and immutable.”

Eventually you’ll also be able to initialize getter-only autoproperties from within constructors, but at the time of writing this article, it is not yet supported in the latest CTP (Visual Studio 14 CTP4).

C# 6 Preview: await in catch and finally blocks

Up until now, you couldn’t put an await in a catch or finally block. That changes in C# 6.

I’ve got this Logger class, whose implementation is pretty trivial. This is how I’m using it in a simple WPF application’s button event handler:

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            using (var logger = new Logger())
            {
                try
                {
                    await logger.LogAsync("Executing operation...");
                }
                catch (Exception ex)
                {
                    await logger.LogAsync(ex.ToString());
                }
                finally
                {
                    await logger.FlushAsync();
                }
            }
        }

As you can see, in C# 6 you can now await asynchronous operations from within your catch and finally blocks, which is very useful in cases such as the above.

C# 6 Preview: Declaration Expressions

Note: although this feature appears to be implemented as an experimental language feature in Visual Studio 14 CTP4, the Roslyn language features page seems to indicate that it won’t be supported. In fact this post seems to confirm that declaration expressions won’t make it into the next version of .NET. Keep this in mind as you continue reading.

Update 14th April 2017: Although this feature did not make it into C# 6, it is now available as from C# 7 (released in 2017).

One of the new features in C# 6 is that we’ll be allowed to declare a variable from within an expression. The most common example of this is in the out parameter of a TryParse() call. Consider this code:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            int x = 0;
            if (int.TryParse(input, out x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

That x declaration is a little annoying – it wastes a line just to declare a variable so that we can get an out parameter into it. In C# 6, we can finally get rid of it:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            if (int.TryParse(input, out int x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

To actually get this working in Visual Studio 14 CTP4 (which is the latest at the time of writing this article), you’ll need to set the LangVersion to Experimental by editing the .csproj file in a text editor and adding the line highlighted below:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>Experimental</LangVersion>
  </PropertyGroup>

Now, I particularly love this feature because I use concurrent collections a lot. And those are full of out parameters. Here’s an example using a ConcurrentDictionary:

            var dict = new ConcurrentDictionary<string, Guid>();
            bool added = dict.TryAdd("user1", Guid.NewGuid());

            bool retrieved = dict.TryGetValue("user1", out Guid user1Guid);
            Console.WriteLine(user1Guid);

            Console.ReadLine();

Now, declaration expressions are useful for more than just out parameters. In fact, if you read Scott Allen’s article on the subject, you’ll see a couple of examples of declarations within conditional and loop expressions. Below is an example of how declaration expressions may be used in a loop:

            foreach (var num in var numbers = Enumerable.Range(1, 10))
                Console.WriteLine("Processing {0} of {1}...", num, numbers.Count());

…and here’s the output of that, just so you get the idea:

Processing 1 of 10...
Processing 2 of 10...
Processing 3 of 10...
Processing 4 of 10...
Processing 5 of 10...
Processing 6 of 10...
Processing 7 of 10...
Processing 8 of 10...
Processing 9 of 10...
Processing 10 of 10...

Finally, here is an example from the Roslyn C# feature descriptions (CTP3) [PDF] which shows how declaration expressions can facilitate the use of out parameters in queries, where declarations were previously not possible:

from s in strings
select int.TryParse(s, out int i) ? i : -1;

C# 6 Preview: using static

Update 31st January 2015: The syntax for using static has changed as from VS2015 CTP5. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Take a look at this little VB .NET program:

Module Module1

    Sub Main()

        Console.WriteLine("Hello world!")
        Console.ReadLine()

    End Sub

End Module

In VB .NET, you can take the Console static class name out of there and put it in the imports:

Imports System.Console

Module Module1

    Sub Main()

        WriteLine("Hello world!")
        ReadLine()

    End Sub

End Module

In fact, that feature works for any static class. And now, this feature is being added to C# starting from version 6. Let’s see the same example in C#. This is as you would write it in C# 5:

using System;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
            Console.ReadLine();
        }
    }
}

And this is how it looks like with the new static using feature in C# 6:

using System.Console;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello world!");
            ReadLine();
        }
    }
}

Although most examples I’ve seen use this kind of scenario, I don’t think it’s a very good example of where this feature is useful. In fact, by extracting the static class name from the code that uses it, we’re reducing readability, and we’re also introducing the risk of ambiguity with other static classes that define the same method names. In this case we can’t add a static using for System.Diagnostics.Trace (which also has a WriteLine() method), but it’s quite easy to write a static Logger class that also defines a WriteLine() method, and that can be problematic.

However, the static using feature can be very useful in code that uses static methods heavily. A good example is mathematical calculations. Consider this code:

using System;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Math.Sin(angle) * Math.Sin(angle) + Math.Cos(angle);
            var denominator = 1 + Math.Sqrt(Math.Sin(angle) + Math.Pow(Math.Cos(angle), 3));

            return Math.Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(Math.PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

We can make it a whole lot more concise by introducing the using static:

using System;
using System.Math;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Sin(angle) * Sin(angle) + Cos(angle);
            var denominator = 1 + Sqrt(Sin(angle) + Pow(Cos(angle), 3));

            return Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

In this case, when you read the code, it’s pretty obvious that Sin(), Cos(), Pow() and Sqrt() are mathematical functions, and it’s also very unlikely that there will be an ambiguity.

So in summary, the using static feature can be useful in some scenarios and disruptive in others. Use it wisely.

C# 6 Preview: nameof expressions

One of the new features in C# 6 is the new nameof operator. This will give you the name of a variable or type name, for instance nameof(id) gives you “id”. It’s a very simple feature. Let’s see a couple of examples where it is useful.

The simplest example is when checking whether arguments are null. I’ve got this simple Person class:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException("firstName");
            if (lastName == null)
                throw new ArgumentNullException("lastName");

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

Notice how I’m passing magic strings into the ArgumentNullExceptions. If I rename the arguments, then I must remember to update the magic strings as well.

Let us now take advantage of the new nameof() operator:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException(nameof(firstName));
            if (lastName == null)
                throw new ArgumentNullException(nameof(lastName));

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

It’s evident that with this change, if you rename the arguments, you will have to rename them throughout, or you will get a compiler error. No more magic strings.

Another scenario where this is really useful is when you are dealing with NotifyPropertyChanged in a WPF application. After implementing INotifyPropertyChanged in my ViewModel, I added the following property with a backing field to facilitate data binding:

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged("CurrentTime");
            }
        }

Here we have the same problem as before: we are using magic strings, and that can be problematic especially if we refactor our property and forget to update the property name in the string. Over the years, MVVM library developers have come up with various ways to mitigate this unpleasant scenario, including passing backing fields as ref parameters when raising the PropertyChanged event, using CallerMemberName, or using expression trees to pass in the property itself. nameof() again makes things a lot easier, as shown below. Even better, it is evaluated at compile-time, so there is no performance penalty associated with its use.

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged(nameof(CurrentTime));
            }
        }

On Detachment and Goodbyes

So as I explained in the welcome post, I am bidding goodbye to Programmer’s Ranch and starting something afresh with Gigi Labs. Programmer’s Ranch was probably my most successful website so far, and it is a little sad to let it go after slightly less than 18 months.

In life we come across many sad moments, and the demise of a blog is certainly among the least significant of these.  Whether we’re talking about a colleague leaving to pursue a new venture, or a friend who is emigrating, or someone close who just passed away, it is never easy to say goodbye.

There’s a nice conversation from Star Wars which I think contains a few nuggets of wisdom that apply in such cases. Taken from this question, here it goes:

Yoda: “Careful you must be when sensing the future, Anakin! The fear of loss is a path to the Dark Side.”

Anakin: “I won’t let my visions come true, Master Yoda.”

Yoda: “Rejoice for those around us who transform into the Force. Mourn them, do not. Miss them, do not. Attachment leads to jealousy, the shadow of greed, that is.”

Anakin: “What must I do, Master Yoda?”

Yoda: “Train yourself to let go of everything you fear to lose.”

This advice might sound a little bit brutal, but I think it depends very much on the interpretation. For me, detachment from the things and people that were an important part of our lives does not mean that we don’t care about them. It merely means that we accept that nothing lasts forever. It is for this reason that we make the most of the time we have available with them. And when the time comes to part ways, and for all the time thereafter, we remember and appreciate the part they played in our lives, and the part we played in theirs. Because each one of us has developed into who we are as a result of the interactions we had with others, much like invisible threads.

This also ties in with Buddhist teachings on attachment and liberation:

“The Buddha saw that people’s ignorance of the nature of change was the cause of suffering. We desire to hold on to what we value, and we suffer when life’s inevitable process of change separates us from those things. Liberation from suffering comes, he taught, when we are able to sever our attachments to the transient things of this world.

[…]

“The challenge is not to rid oneself of attachments but, in the words of Nichiren, to become enlightened concerning them. […]

“In their proper perspective–when we can see them clearly and master them rather than being mastered by them–desires and attachments enable us to lead interesting and significant lives.”

So perhaps Yoda will be disappointed to find out that we’ll still miss the people who are no longer a part of our lives. However I think he’d be pretty proud of us if, whenever a friend leaves for greener pastures (whether it means a new job, a new country, or whatever), we know in our heart that we played an important part in his/her personal development, and life in general.

Welcome to Gigi Labs

Hello everyone, and welcome to Gigi Labs!

This is not my first website, nor my first blog. I’ve actually been writing on the web for the past 12 years, starting with Dino’s Ultima Page and subsequently launching various different sites, some of which still exist today (such as Gigi’s Computer Corner). My most recent website was Programmer’s Ranch, a highly successful blog in which I would explain various programming topics in a concise and practical manner.

Programmer’s Ranch was based on the Blogger platform, which turned out to be a pretty poor choice for various reasons. It was very time-consuming to write decent-quality programming articles on a CMS that had no support whatsoever for syntax highlighting, among various other deficiencies. Less than 18 months after Programmer’s Ranch was launched on 2nd May 2013, I now find myself needing to create a new blog – Gigi Labs.

With Gigi Labs, I am taking things to a whole new level. Aside from continuing the legacy of Programmer’s Ranch with programming articles, I will also be writing about various other topics including PC games, music, workplace, etc.

This is a bit of a departure from my previous websites, which were each dedicated to a different aspect of my life and were completely hand-coded from the ground up (other than the blogs, naturally). For Gigi Labs I am using the power of the WordPress CMS to write about various topics and have them categorised neatly. Gigi Labs is where all those websites I created over the past 12 years converge.

Thanks for following Gigi Labs!

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