Another nice feature in C#6.0

Ok, so it’s technically Christmas and I should really be eating too many mince pies and watching repeats of early 80s sitcoms instead of blogging. But somehow I can’t stop technology catching my eye.

I was reading a blog post from John Skeet on the subject of C# 6.0 features the other day, and noticed that somewhere along the line they snuck in something I’d not noticed before: The nameof() expression. I’m not entirely sure how I managed to miss this, as apparently it’s been in the spec since 2013 – but I’m pleased to see it.

This expression returns the string representation of the name of whatever you pass to it – locals, range variables, parameters, type parameters, members, types or namespaces. And there are lots of places where that could be useful. Especially when throwing exceptions that need to include the name of a parameter. (for example checking if the parameter was null) It gets rid of the need to have string constants for the parameter name – and hence also gets rid of a potential refactoring bug where you change the name of a parameter, and forget to rename the string constant representing it in an exception message at the same time.

But it struck me that there’s potential here for making some simple Sitecore code a bit nicer here too. Consider the scenario where you want a simple wrapper class for an Item but for some reason you don’t want a fully fledged ORM in your code. You could potentially write:

public class MyPageModel
{
    public string PageTitle { get; private set; }

    public MyPageModel(Item source)
    {
        this.PageTitle = source.Fields[nameof(this.PageTitle)].Value;
    }
}

In a similar way, it gets rid of the need for a string constant, and hence the potential for an error. And it makes life a bit easier if you’re auto-generating this code through T4 Templates or similar.

I can see myself using that, along with the null coalescing operator I’ve commented on before.

Advertisements

One thought on “Another nice feature in C#6.0

  1. It’s interesting to see the C# syntax becoming more like Ruby and less like C++…

    Now we need an “unless” statement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s