In the nameof*
The nameof operator takes a code element then it returns a string literal with the same name. This is evaluated at compile time and has no effect at runtime.
Aug 23, 2019 • 5 Minute Read
Introduction
On the 12th day of November back in 2014, Microsoft announced the preview version of Visual Studio 2015. They also announced a new version of C# which was, at that time, 6.0. This update came with many new features.
- String interpolation
- Exception filtering
- Auto property initializer
- Static class statements
- Dictionary initializers
- Using the await in catch and finally blocks
- Null propagation operator
This list of features is just a showcase of how big of a step version 6.0 was back in 2014. Now, the most important feature we care about is the nameof operator.
nameof
If we want to cut things short, all this operator does is it takes a code element, which can be a class or any of its member methods, variables, or constants, then it returns a string literal with the same name. This is evaluated at compile time and has no effect at runtime.
Let's start with a simple demo.
string Pluralsight = "This is a written guide!";
Console.WriteLine($"The variable with name: {nameof(Pluralsight)}, holds the value: {Pluralsight}");
This gives us the following result.
The variable with name: Pluralsight, holds the value: This is a written guide!
This gives more elegance to the code along with making it easier to track the property that is used and the literal name of the property.
Before version 6.0 of C#, there was a very common task which happened a lot in the programming world. This task is still common, but the overhead is reduced by our new nameof operator. Namely, this task was about sending a notification when a property of an object changed. This bellow snippet of code is from a very simple game I wrote last year about monsters and heroes. There is nothing fancy about it but the nameof operator shows its strength. Without the operator, my code would have looked like this:
public bool isAlive
{
get
{ return _isAlive; }
set
{ this.OnPropertyChanged("isAlive"); }
}
With the operator it looks like this.
public bool isAlive
{
get
{ return _isAlive; }
set
{ this.OnPropertyChanged(nameof(isAlive)); }
}
For me, this was a big game changer since it alleviated the need to write the property names as strings and pass them as the argument for the OnPropertyChanged event.
Another example should further solidify the concept in you.
using System;
using System.Text;
namespace NameOfFeature
{
public class Worker
{
public Worker(string name, string title, string company)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
else
Console.WriteLine("Name: " + name);
if (title == null)
throw new ArgumentNullException(nameof(title));
else
Console.WriteLine("Location: " + title);
if (company == null)
throw new ArgumentNullException(nameof(company));
else
Console.WriteLine("Age: " + company);
}
static void Main(String[] args)
{
Worker d = new Worker("Dániel", "DevOps Engineer", "Itronlabs");
Console.Read();
}
}
}
The following output is produced upon execution.
Name: Dániel
Location: DevOps Engineer
Age: Itronlabs
In this example, we saw that the nameof operator helps us to create a more concise application by not stringifying the properties or arguments of our constructor, by simply utilizing the feature.
You also have the option to specify type and namespace but the produced string literal is not fully qualified!
Console.WriteLine(nameof(System.Collections.Generic));
The following output welcomes us.
Generic
Let's create another example with a list of integers; more specifically, odd numbers.
List<int> oddNumbers = new List<int> { 1, 3, 5, 7, 9, 11 };
Console.WriteLine(nameof(oddNumbers.Add));
Console.WriteLine(nameof(oddNumbers.Count));
Console.WriteLine(nameof(oddNumbers.FindAll));
Console.WriteLine(nameof(oddNumbers.ForEach));
Console.WriteLine(nameof(oddNumbers.IndexOf));
Console.WriteLine(nameof(oddNumbers.Remove));
Upon executing the above code, we see the following on the console:
Add
Count
FindAll
ForEach
IndexOf
Remove
This is also a great example of the feature the operator brought to our lives.
In Foof We Trust: A Dialogue is a link to a very popular dialogue created by Eric Lippert. It pretty much sums up why the infoof, the predecessor of nameof, failed and why nameof succeeded.
Conclusion
In this guide, you saw a relatively new operator which made quite the difference in the lives of many programmers. From the examples we looked at, you might get the sense that this is not that big of a step forward - this is what I thought at first - . But then, the more and more I got into using it, the more I started to appreciate it. I honestly hope that this was worth your while, and your toolset was increased by at least one item after reading this article.