Nameof expressions is yet another cool and awesome little feature which helps you to avoid magic strings in your code base.

Here is a little example of what nameof expressions essentially try to solve:

public void Greet(string name) 
    if (name == null) throw new ArgumentNullException("name"); 
    // Do other stuff.. }

This introduces ‘magic strings’ in the sense that you get no compile time validation and it’s also prone to errors. Furthermore you can also get out of sync when refactoring the method signature, as it could possibly leave the string literal “name” unchanged.

C# 6.0 – Nameof Expressions

With C# 6.0 we can turn the above example into:

public void Greet(string name) 
    if (name == null) throw new ArgumentNullException(nameof(name)); // nameof(name) outputs: name 

The nameof operator provides access to element names such as a class, method, parameter, property, field or variable and returns its string literal. You can also dot navigate in nameof expressions however only the final identifier will be used.

Here is an example of that:

Console.WriteLine(nameof(user.Points)); // Outputs: Points

That’s it for now!