nameof Operator in C#

C# 6.0 introduced a new operator named, nameof  that accepts the name of code element and returns a string literal of the same element.  The nameof operator can take as a parameter like class name and its all members like method, variables, properties and return the string literal.  This avoids having hardcoded strings to be specified in our code as well as avoid explicitly use of reflection to get the names.

Below is the simple code snippets that show the uses of nameof operator.

class Program
{
    static void Main(string[] args)
    {
        WriteLine(nameof(Student));
        WriteLine(nameof(Student.Roll));
        WriteLine(nameof(Student.Name));
        WriteLine(nameof(Student.Address));
    }
}

class Student
{
    public int Roll { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

The output would be like below :image_thumb

Advertisements
nameof Operator in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s