C# 6.0 New Features - nameof Operator

development, csharp comments edit

Personally I think this one is a bit trivial. So the argument is it eliminates the need for using hard-coded strings in the code.

For instance:

public class NameofOperator
{
    public void Run(SomeClass someClass)
    {
        if (someClass == null)
        {
            throw new ArgumentNullException("someClass");
        }
    }
}

public class SomeClass
{
}

Say you refactored the code and changed the parameter name in this example. It is likely to forget changing the name in the exception throwing line since it has no reference to the actual parameter.

By using nameof operator we can avoid such mistakes:

public class NameofOperator
{
    public void Run(SomeClass refactoredName)
    {
        if (refactoredName == null)
        {
            throw new ArgumentNullException(nameof(refactoredName));
        }
    }
}

public class SomeClass
{
}

The results are identical but this way when we change a parameter name all references to that object will be updated automatically.

Comments