The nameof operator new feature available in C# 6.0. By using the nameof operator, we can get the name of the variable, type, or a method and so on. This is very helpful operator when we want to raise the exception for a variable, whenever we need to get the name of a method or variable or event, whenever we need to check property name and many others. Open Microsoft Visual Studio 2015 and create C# Console Application.
using System;
namespace CSharpNameOf
{
class Program
{
static void Main(string[] args)
{
string strName = null;
if (strName == null)
{
throw new ArgumentNullException(nameof(strName));
}
}
}
}
As shown above we are throwing argument null exception with the variable name if the variable is null. Run the application, and it throws the null exception with variable name strName as shown below.
We can use nameof operator to check the condition in a switch statement as shown below.
switch (e.PropertyName)
{
case nameof(property1):
{ break };
case "There is no property":
{ break; }
}
Even we can return the method name also by using the nameof operator.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The method name to get sum of two integers is " + nameof(Add));
Console.ReadLine();
}
private int Add(int n1, int n2)
{
return n1 + n1;
}
}