C# language feature:

  • nameof operator

applies to

  • variable names in code

benefit

  • Improves coding maintainance. Avoids hard coding of a variable name in error messages, logs, etc. i.e. facilitates refactoring/renaming variables.

how to use

  • Replace string literal reference to variable with nameof(variable).

example:

        public string sirName;  // if this variable name is refactored/renamed the exception below will accurately reflect the renaming/refactored variable name
        public string LastName
        {
            get { return sirName; }
            set
            {
                if (value != sirName)
                {
                    throw new ArgumentException(message: "Name Changed", paramName: nameof(sirName));

                    // previously the following would cause confusion after a rename/refactoring of sirName.
                    throw new ArgumentException(message: "Name Changed", paramName: "sirName");
                }
            }
        }