The nameof operator in C# is a simple but powerful feature that helps you avoid hardcoding strings in your code. It returns the name of a variable, type, or member as a string.
nameof?Refactor-Friendly: If you rename a variable or member, nameof automatically updates.
Avoid Magic Strings: Reduces errors caused by typos in string literals.
Improves Readability: Makes it clear what you’re referring to.
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
public void ValidateUser(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (string.IsNullOrEmpty(user.Name))
{
throw new ArgumentException("Name cannot be empty", nameof(user.Name));
}
}Refactoring:
If you rename user to userProfile, nameof(user) will automatically update to nameof(userProfile).
Avoiding Magic Strings:
Instead of throw new ArgumentNullException("user"), use nameof(user) to avoid typos.
Common Use Cases:
Argument validation (e.g., ArgumentNullException).
Logging (e.g., logger.LogDebug($"{nameof(User)} created")).
Data binding in UI frameworks (e.g., WPF, Xamarin).
nameof only works with compile-time symbols (e.g., variables, properties, types). It won’t work with runtime values or expressions.