A Nice Little C# Gem

One of the built-in operators that I like in C# is nameof(). Given an identifier, nameof returns a string which contains the identifier. Typically, it gets used for argument checking:

public void BeExcellent(int input)
{
    if (input < 0) {
        throw new ArgumentOutOfRangeException (nameof (input));
    }
}

But there’s more that you can do with nameof(). I saw some code yesterday that looked like this:

public static const string Operator = "Operator";
public static const string Constant = "Constant";
public static const string Expression = "Expression";

Using nameof(), we change it to this:

public static const string Operator = nameof (Operator);
public static const string Constant = nameof (Constant);
public static const string Expression = nameof (Expression);

This nice thing about this is that typos are consistent – if you make a typo in the symbol name, it will be in the string instead of the possibility of there being a typo only in the string or only in the symbol. Also if you need to refactor and change the name of a symbol, you can do everything in one shot with your refactoring tools as it should be.

What surprised me about this is from the way that compilers are built. When you have binding expression of the form type symbol = expr, usually the symbol is hidden from the the expression. It’s a convenience that prevents bad code of referencing an unbound symbol, but in this case it does work and it makes sense for it to work since we don’t care about the value of symbol, just its name.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.