C# Tip: nameof

Juarez Júnior - Sep 11 - - Dev Community

Let’s explore the nameof operator, introduced in C# 6, which allows you to get the name of variables, methods, and properties in a safe and efficient way, especially useful for logs and validations. See the example in the code below.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }

    public void UpdatePrice(decimal newPrice)
    {
        if (newPrice != Price)
        {
            Console.WriteLine($"{nameof(Price)} updated from {Price:C} to {newPrice:C}");
            Price = newPrice;
        }
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Product: {Name}, {nameof(Price)}: {Price:C}");
    }
}

public class Program
{
    public static void Main()
    {
        Product product = new Product("Pen", 2.99m);
        product.DisplayInfo();

        product.UpdatePrice(3.49m); // Logs the price change
        product.DisplayInfo();
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
The nameof operator is incredibly useful when you want to reference the name of variables, properties, or methods safely. This makes refactoring easier by avoiding hardcoded strings in validations and logs. In the example above, we use nameof to generate log messages and validations without needing to manually write the property names, ensuring that if the variable name changes, nameof will be automatically updated by the compiler.

Source code: GitHub

I hope this tip helps you use the nameof operator to write safer and more maintainable code! Until next time.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player