0007 Using nameof for Cleaner Code

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.

Why use nameof?

Example:

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));
    }
}

Key Points:

  1. Refactoring:

  2. Avoiding Magic Strings:

  3. Common Use Cases:


Gotcha: