The purpose of nameof is refactoring. For example, when you change the name of a class to which you refer through nameof somewhere else in your code you will get a compilation error which is what you want. If you didn’t use nameof and had just a plain string as a reference you’d have to full-text search for the name of the class in order to change it. That’s a pain in the bottom. With nameof you can rest easy, build, and get all the cases for change automatically in your IDE.
For example:
public void DoStuff(object input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } }
If you change the name of the variable, the code will break instead of returning an exception with an incorrect message.
Of course, the uses are not limited to this simple situation. You can use nameof
whenever it would be useful to code the name of a variable or property.
The uses are manifold when you consider various binding and reflection situations. It’s an excellent way to bring what were run time errors to compile time.