Home > dotnet > Safer C# with the nameof expression

Safer C# with the nameof expression

Future-proofing your dotnet strings for validation and property changed events

by

Originally posted at KillAllDefects on October 29, 2019

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 expression and how it can improve maintainability while reducing defects.

Introducing the C# nameof Expression

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

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

private int favoriteNumber = 42;

public int FavoriteNumber
{
   get
   {
       return favoriteNumber;
   }
   set
   {
       if (favoriteNumber != value)
       {
           favoriteNumber = value;
           OnPropertyChanged("FavoriteNumber");
       }
   }
}

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 such as UWP will not properly refresh the UI.

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

private int favoriteNumber = 42;

public int FavoriteNumber
{
   get
   {
       return favoriteNumber;
   }
   set
   {
       if (favoriteNumber != value)
       {
           favoriteNumber = value;
           OnPropertyChanged(nameof(FavoriteNumber));
       }
   }
}

The way this works, is the compiler evaluates the nameof expression 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 the C# nameof expression 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 expression, 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.

Argument validation code like the following is common to see in dotnet code:

public string FetchDataFromRepository(IRepository repository, int id)
{
   if (repository == null) throw new ArgumentNullException("repository");
   if (id <= 0) throw new ArgumentOutOfRangeException("id");

   // Actual logic goes here

   return "Placeholder data";
}

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 expression is a perfect solution to this problem:

public string FetchDataFromRepository(IRepository repository, int id)
{
   if (repository == null) throw new ArgumentNullException(nameof("repository"));
   if (id <= 0) throw new ArgumentOutOfRangeException(nameof("id"));

   // Actual logic goes here

   return "Placeholder data";
}

Closing Thoughts on the C# nameof expression

The C# nameof expression 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 expression in mind when writing code in C#.

Author

  • Matt Eland

    After several decades as a software engineer and engineering manager, Matt now serves as a software engineering instructor at Tech Elevator where he gets to raise up future developers and unleash them upon the world to build awesome things. Matt is an Azure Data Scientist and AI Engineer Associate, runs a data science blog and YouTube channel, is currently pursuing a master's degree in data analytics, and helps organize the Central Ohio .NET Developer Group. In his copious amounts of spare time, Matt continues to build nerdy things and looks for ways to share them with the community.

Leave a Reply

Related Content

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More