nameof Operator in C# 6.0

C# 6.0 Features Series

C# 6.0 introduces the new nameof operator that returns the name of the program element.

For example , assume that you want to throw the ArgumentNullException for a parameter , you would do something like the code snippet shown in the earlier version of C#.

public void PerformAction(Point point1, Point pointy)
{
    if(point1 == null)
    {
        throw new ArgumentNullException("point1");
    }
}

In the above code snippet , the ArgumentNullException takes the parameter of type string with the name of the parameter point1 . Now , if you refactor this method by renaming the parameter point1 to pointx , the parameter of ArgumentNullException still remains as “point1” . This might lead to inconsistency.

The nameof operator solves this problem . You could rewrite the above code snippet as shown below.

public void PerformAction(Point point1, Point pointy)
{
    if(point1 == null)
    {
        throw new ArgumentNullException(nameof(point1));
    }
}

Now , when you rename the first parameter “point1” , the corresponding name used with the nameof operator would also be updated.

No Responses

Leave a Reply