C# feature nameof

Hello everybody,

today I want to share with you one cool feature of C#.  It is nameof. Take a look at the following code:

var abc = 3;
var varName = nameof(abc);

How do you think, what will go into varName? It will be equal to "abc". Probably you can puzzle why on earth I can need such an operator?

Consdier following cases:

1. If you work with reflection, then instead of rely on hard coding names of fields, you can rely on compiler to subsitute it instead of you. 

class Program
{
    public class NameOffDemo
    {
        public string SomePropertyOne { getset; }
        public string SomePropertyTwo { getset; }
    }
 
    static void Main(string[] args)
    {
        var demo = new NameOffDemo();
 
        //lets say you somehow read via reflection demo.
        //Here for demo purposes I hard code it, but you can have 
 
        string neededProperty = "SomePropertyTwo";
 
        switch (neededProperty)
        {
            case nameof(demo.SomePropertyOne):
            {
                break;
            }
 
            case "SomePropertyTwo":
            {
                //Compare hard coding and maintenance for the future
                break;
            }
 
        }
    }
}

As you can see from the presented code, if in future somebody will change the name of variable, the code will not be compilable untill person will fix it. But if hard-code strings, then compiler will pass this code, and during runtime you'll see the error.

2. For reading values from cofnig files. Consider following example:

public static readonly bool ParallelProcessing = WebConfig.GetBool(nameof (ParallelProcessing), true);

In this case you'll be able to read value from config file without hard coding it in your C# code.

If to summarize, nameof allows you to be compile time safe. 

No Comments

Add a Comment