I had an issue yesterday with some code I found on the internet and realized that the implementation was probably not exactly what was intended.

Let’s look at a much simplified version of that code that illustrates the problem:

public static class SharedResources{
    public static IList<Color> Colors => new List<Color>();
}

class Program
{
    static void Main(string[] args)
    {
        var colors = new [] { Color.Red, Color.White, Color.Blue};
        foreach (var color in colors)
        {
            SharedResources.Colors.Add(color);
        }
        Console.WriteLine(StaticResources.Colors.Count);
    }
}

If you run this code, you will find that the StaticResources.Colors is empty. At first glance, one would expect the StaticResources.Colors to have 3 elements. What’s going on? Is C# broken? The problem here is that the property Colors in the SharedResources class is initialized using what is called an Expression bodied member and was introduce in C#6. It’s a mouth full I know but it is nothing else than syntaxic sugar for:

public static IList<Color> Colors
{
    get
    {
        return new List<Color>();
    }
}

What should have been used instead is an initializer for read-only auto-property which was also introduce in C#6.

public static IList<Color> Colors {get;} =  new List<Color>();

which is equivalent to the following code

private readonly static List<Color> _colors = new List<Color>();

private static IList<Color> Colors 
{
    get
    {
        return _colors;
    }
}

With this little change, the auto-property Colors is only initialized once and the code works as expected.

Don’t get me wrong. I love the new syntaxic features that shipped with C#6 and I use them all the time. The code intent is clear and we can reduce the syntaxic noise greatly.

That being said Friends, it’s not always easy to find those mistakes on real code. So beware!