Author avatar

Dániel Szabó

In the nameof*

Dániel Szabó

  • Aug 23, 2019
  • 5 Min read
  • 21 Views
  • Aug 23, 2019
  • 5 Min read
  • 21 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.

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

This gives us the following result.

1
The 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:

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

With the operator it looks like this.

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

}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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();
        }
    }
}
csharp

The following output is produced upon execution.

1
2
3
Name: Dániel
Location: DevOps Engineer
Age: 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!

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

The following output welcomes us.

1
Generic
bash

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

1
2
3
4
5
6
7
8
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));
csharp

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

1
2
3
4
5
6
Add
Count
FindAll
ForEach
IndexOf
Remove
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.

0