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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...