Author avatar

Dániel Szabó

In the nameof*

Dániel Szabó

  • Aug 23, 2019
  • 5 Min read
  • 1,188 Views
  • Aug 23, 2019
  • 5 Min read
  • 1,188 Views
Languages Frameworks and Tools
C#

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.

  1. String interpolation
  2. Exception filtering
  3. Auto property initializer
  4. Static class statements
  5. Dictionary initializers
  6. Using the await in catch and finally blocks
  7. 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.

1string Pluralsight = "This is a written guide!";
2Console.WriteLine($"The variable with name: {nameof(Pluralsight)}, holds the value: {Pluralsight}");
csharp

This gives us the following result.

1The variable with name: Pluralsight, holds the value: This is a written guide!
bash

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:

1public bool isAlive
2{
3	get
4	 { return _isAlive; }
5	set
6	 { this.OnPropertyChanged("isAlive"); }
7}
csharp

With the operator it looks like this.

1public bool isAlive
2{
3	get
4	 { return _isAlive; }
5	set 
6	 { this.OnPropertyChanged(nameof(isAlive)); }
7
8}
csharp

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.

1using System;
2using System.Text;
3
4namespace NameOfFeature
5{
6    public class Worker
7    {
8        public Worker(string name, string title, string company)
9        {
10            if (name == null)
11                throw new ArgumentNullException(nameof(name));
12            else
13                Console.WriteLine("Name: " + name);
14
15            if (title == null)
16                throw new ArgumentNullException(nameof(title));
17            else
18                Console.WriteLine("Location: " + title);
19
20            if (company == null)
21                throw new ArgumentNullException(nameof(company));
22            else
23                Console.WriteLine("Age: " + company);
24        }
25        static void Main(String[] args)
26        {
27            Worker d = new Worker("Dániel", "DevOps Engineer", "Itronlabs");
28            Console.Read();
29        }
30    }
31}
csharp

The following output is produced upon execution.

1Name: Dániel
2Location: DevOps Engineer
3Age: Itronlabs
bash

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!

1Console.WriteLine(nameof(System.Collections.Generic));
csharp

The following output welcomes us.

1Generic
bash

Let's create another example with a list of integers; more specifically, odd numbers.

1List<int> oddNumbers = new List<int> { 1, 3, 5, 7, 9, 11 };
2
3Console.WriteLine(nameof(oddNumbers.Add));
4Console.WriteLine(nameof(oddNumbers.Count));
5Console.WriteLine(nameof(oddNumbers.FindAll));
6Console.WriteLine(nameof(oddNumbers.ForEach));
7Console.WriteLine(nameof(oddNumbers.IndexOf));
8Console.WriteLine(nameof(oddNumbers.Remove));
csharp

Upon executing the above code, we see the following on the console:

1Add
2Count
3FindAll
4ForEach
5IndexOf
6Remove
bash

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.