DEV Community

Nick
Nick

Posted on

Nameof in C#

C# Nameof is a feature in C# that allows you to get the name of a variable, type, or member as a string. This can be useful for things like logging, debugging, and reflection. Let's take a look at how Nameof works with some code examples.

using System;

public class Example
{
    public string Name { get; set; }

    public void DisplayPropertyName()
    {
        string propertyName = nameof(Name);
        Console.WriteLine(propertyName); // Output: Name
    }
}

public class Program
{
    public static void Main()
    {
        Example example = new Example();
        example.DisplayPropertyName();

        string typeName = nameof(Example);
        Console.WriteLine(typeName); // Output: Example
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we have a class Example with a property Name and a method DisplayPropertyName that uses nameof to get the name of the property. By using nameof(Name), we can avoid hardcoding the property name as a string, which can help prevent errors if the property name changes in the future.

In the Main method, we also use nameof(Example) to get the name of the Example class as a string. This can be useful for things like generating dynamic SQL queries or working with reflection.

Overall, C# Nameof is a handy feature that can improve the maintainability and readability of your code by removing hardcoded strings and making it easier to reference variable names, type names, and member names. Give it a try in your own projects and see the benefits for yourself!

Top comments (0)