nameof Operator



The use of the name Operator
In an error-prone code, when we want to get the name of a variable, class, or method, C# NameOf operator is used. It returns a simple string as a result.

We can use it for logging, validating parameters, checking events, etc.

Example:

using System;  
namespace NameOfOperator
{  
    class NameOfOperatorClass
    {  
        public static void Main(string[] args)  
        {  
            string name = "Mohit Kumar";  
            // Accessing name of variable and method  
            Console.WriteLine("Variable name is: "+nameof(name));  
            Console.WriteLine("Method name is: "+nameof(showDetail));  
        }  
        static void showDetail()  
        {  
            // code
        }  
    }  
}  

Output:

Variable name is: name
Method name is: showDetail

0 Comment's

Comment Form