Guitar Tab – Prayer in C by Lilly Wood and The Prick

If you’ve heard the Robin Schulz remix of Prayer in C by Lilly Wood and The Prick, or even the original, you’ll recognise the catchy guitar tune. As the name suggests, it’s in the key of C, and that means no sharps or flats. The tune goes something like:

  • A A B C B A E
  • E F E D
  • D E F D
  • F F G F

This could translate to the following guitar tab:

e|--5-57875--------------------
B|---------5--565----56---6-686
G|---------------7--7--7-------
D|-----------------------------
A|-----------------------------
E|-----------------------------

This is not very different from other guitar tabs for this song out there, but it has the advantage that the notes are concentrated between the 5th and 8th fret, allowing you to play the tune without ever needing to slide your left hand.

C# 6 Preview: Index initializers

Dictionary initializer syntax is pretty convenient, but has always been somewhat awkward to use. It doesn’t really feel like you’re working with a dictionary at all. Let’s borrow some sample code from C# Basics: Morse Code Converter Using Dictionaries, one of my early articles at Programmer’s Ranch:

            Dictionary<char, string> morse = new Dictionary<char, string>()
            {
                {'A' , ".-"},
                {'B' , "-..."},
                {'C' , "-.-."},
                {'D' , "-.."},
                {'E' , "."}
                //...
            };

C# 6 offers an alternative syntax just for the sake of making this kind of thing more intuitive:

            Dictionary<char, string> morse = new Dictionary<char, string>()
            {
                ['A'] = ".-",
                ['B'] = "-...",
                ['C'] = "-.-.",
                ['D'] = "-..",
                ['E'] = ".",
                //...
            };

For the purpose of initialising a dictionary, you can pretty much assume that the two syntaxes above are semantically, equivalent, even though that is not entirely true. Scott Allen’s What’s New in C# 6 course on Pluralsight demonstrates that the original syntax is translated into dictionary .Add() calls, while the new one is translated into index assignments.

It is also not permitted to mix the two syntaxes above.

Note: according to the official C# feature descriptions (PDF), index initializers supposedly “do not work in the current CTP”, however the above example worked just fine in Visual Studio 14 CTP 4.

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
        {
            get
            {
                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:

struct-parameterless-constructors-vs2012

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' ">
    <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>

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:

struct-parameterless-constructors-vs14ctp4

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:

            try
            {
                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)
            {
                Console.WriteLine("Doh");
            }

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)
        {
            try
            {
                throw new InvalidOperationException("Invalid operation",
                    new Exception("Justin Bieber is breathing"));
            }
            catch(Exception ex) if (ex.InnerException != null)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("  -->{0}", ex.InnerException.Message);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }

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)) {}

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