C# Interview Question #109
What is nameof in C#, and why is it useful?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
nameof returns the source-code name of a variable, type, property, method, or other symbol as a string.
Detailed Explanation
nameof returns the source-code name of a variable, type, property, method, or other symbol as a string.
It is preferable to hard-coded member names because refactoring tools and the compiler can keep the reference consistent when symbols are renamed.
nameof is commonly used in exceptions, validation, logging, property-change notifications, and diagnostics.
Code Example
public void SetPrice(decimal price)
{
if (price < 0)
throw new ArgumentOutOfRangeException(nameof(price));
}