loading...
Cover image for Safer C# with the nameof operator
Tech Elevator

Safer C# with the nameof operator

integerman profile image Matt Eland Originally published at killalldefects.com on ・3 min read

C# 6 introduced a simple operator that can prevent several types of issues if properly used. In this short article, we’ll explore the nameof operator and how it can improve maintainability while reducing defects.

Introducing the nameof operator

The nameof operator substitutes the name of a named member at compile time.

Let’s take a look at some WPF code that could benefit from this operator:

The old notify property changed pattern without using nameof.

This example exposes a property changed event as part of implementing INotifyPropertyChanged. Because of that, it’s important that the property name match the string passed in to OnPropertyChanged. If these don’t match up well, WPF and other XAML-based frameworks will not properly refresh the UI.

Instead of hard-coding a string name here, we can make a small change and use the nameof operator like so:

Notify Property Changed using the C# 6 nameof operator.

The way this works, is the compiler evaluates the nameof operator at compile time and substitutes the name of the member being referenced into the generated binary. This means that the end result is going to be the same as the earlier example.

Note: if you’re using XAML-based technologies, I recommend you also consider using caller member info for property changed notifications.

Okay, so how is this useful?

If nameof can’t resolve the name of the member you’re referencing, you will get a compiler error and be forced to resolve it. That means that if you misspell the name of a member or you change a method name later that nameof pointed to, you’ll know about it as soon as you try to build.

This means that when you use the nameof operator, you’re no longer in danger of using a misspelled or out-of-date string.

Okay, I get it. You probably don’t do any XAML-based development. Fine.

I bet you do at least occasionally perform argument validation.

Code like the following is usually common in codebases:

Argument validation without the nameof operator

Developers don’t usually think to search for string references when renaming parameters to methods, so you sometimes see incorrect or misspelled parameter names provided to the ArgumentException family of exceptions.

In fact, code like this is open copied and pasted without thought because it can tend to be boilerplate logic. Because of this, it’s not extremely uncommon to see the wrong parameter name entirely being provided to the exception. That’s a recipe for debugging pain.

The nameof operator is a perfect solution to this problem:

Argument validation using the nameof operator


Nameof is not going to revolutionize the way you write code, but it is likely to improve the maintainability and accuracy of the code – at least a little bit.

If you’d like to learn more, I recommend starting with Microsoft’s documentation.

Every little thing helps, and so I recommend you keep the nameof operator in mind when writing code in C#.

The post Safer C# with the nameof operator appeared first on Kill All Defects.

Discussion

pic
Editor guide
Collapse
cakekindel profile image
Orion Kindel

Put your braces on the next line you monster 😜

Collapse
integerman profile image
Matt Eland Author

I do this in honor of Halloween.

No, in all seriousness, sorry - I didn't want to spin up Visual Studio for a quick code sample and so I did it in Carbon. My JavaScript brace style seeped in. Like a creature from the abyss.

Collapse
cakekindel profile image
Orion Kindel

I have the same problem 😆 no worries at all hahaha

Collapse
metalmikester profile image
Michel Renaud

That would have saved us a lot of headaches on a project a few years ago where we had several hundred properties using INotifyPropertyChanged. I got to use it on a smaller project a couple of years ago. Very handy.

Collapse
buinauskas profile image
Evaldas

I love this, it becomes really useful for Dapper(or any other raw SQL) statements to guarantee properly mapped objects.

var sql = $@"
    SELECT
        CustomerId AS {nameof(Customer.Id)}
      , CustomerName AS {nameof(Customer.Name)}
      , CustomerBalance AS {nameof(Customer.Balance)}
    FROM dbo.Customers
    WHERE CustomerId = @CustomerId;";
Collapse
integerman profile image
Matt Eland Author

Oh that's fantastic. I hadn't even thought of that use case. Love it!