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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...