C# › Fundamentals

How does the C# 'nameof' operator work, and why is it preferred over hardcoding a string literal for things like argument names in exceptions?

Advanced

Answer

'nameof(expression)' returns the SIMPLE NAME of a variable, type, or member as a compile-time-checked string constant — using it instead of a hardcoded string means renaming the variable/parameter via a refactoring tool automatically updates the nameof() reference too, whereas a hardcoded string would silently become stale and incorrect.
public void SetAge(int age) {
  if (age < 0) throw new ArgumentOutOfRangeException(nameof(age), "Age cannot be negative");
  // nameof(age) automatically stays correct even if the parameter is later renamed
}
Real-world example Ensuring exception messages referencing a parameter name stay accurate even after a rename refactor, rather than silently going stale.

Common follow-ups: Does nameof() incur any runtime cost, given it looks like it's inspecting a variable dynamically?