Jeremy Davis
Jeremy Davis
Sitecore, C# and web development
Article printed from: https://blog.jermdavis.dev/posts/2014/another-nice-feature

Another nice feature in C#6.0

Published 22 December 2014
Updated 25 August 2016

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.

↑ Back to top