When writing code we need to know the name of the type member such as method or property name.The way we access member name in prior versions of C#6 is by hardcoding the
member name.
For example suppose we want to log the name of the method in which error occurs.So we pass the hardcoded name of the method to the log method.
Log(“Display”);
Though the above solution works it has one big problem ,when refactoring the code if we change the name of the Display method to DisplayDetails then the refactoring tool has no way to know that.Since we have hardcoded the method name so the only solution is to manually search in the code for the method name and replace the string Display with the string DisplayDetails
Suppose the Logger class is defined as:
public static class Logger:ILogger { public static void Log(string message) { Console.WriteLine(message); } } interface ILogger { void Log(string message); }
Then in previous versions of C# to log the details such as method name we had to write the code as:
class Employee { public void Display() { Logger.Log("Display"); Logger.Log("Employee"); } }
The problem with the above code occurs when we refactor the Employee class.Suppose we change the name of the Display method to DisplayDetails.Even though we modify the name of the method our existing logging code will continue to log the previous name of the method.Since we have hardcoded the method and type names refactoring tools will not be able to identify this change.
So the only solution is to manually update the hardcoded string values.If we are doing this at lots of places in our code then it can be a really challenging task.
The nameof operator in C# 6 provides a solution to this problem.Instead of hardcoding the method or type names we pass the method name or type names and it is recognized by the nameof operator
class Employee { public void Display() { Logger.Log(nameof(Display)); Logger.Log(nameof(Employee)); } }
So even if we now refactor our code and change the method or type name compiler will identify this.As we are passing the names of the method and types rather than hardcoded string values compiler will recognize if a method or type doesn’t exists and our code will not compiled.
Following are some of the main points about the nameof operator
- The argument to nameof can be a simple member name or a qualified member name
- The argument to nameof operator can be a type name
- Though the argument contains the type or member names,type are not instantiated when we use the argument.
Some of the places where nameof operator can be useful is while logging details or while exception handling.
Leave a Reply