Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does nameof work?

Tags:

c#

c#-6.0

I was just wondering how come nameof from C# 6, can access non static property just like if it was static. Here is an example

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

public class Test
{
    public Test()
    {
        string name = nameof(TestClass.Name); // whats so speciall about nameof
        //string name2 = TestClass.Name; this won't compile obviously, 
    }
}
like image 660
adminSoftDK Avatar asked Sep 10 '16 14:09

adminSoftDK


People also ask

What is Nameof method?

A nameof expression produces the name of a variable, type, or member as the string constant: C# Copy.

Is Nameof reflection?

nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!

When was Nameof added to C#?

The nameof operator, added in C# 6.0, addresses this — it allows capturing the string names of symbols that are in the scope. In the example below, ReSharper suggests the replacement of the string literal "order" in the argument of the ArgumentNullException() with the nameof(order) .


2 Answers

It's not "accessing" the property - that operator is purely a compiler mechanism to inject the "name" of the argument into the code. In this case it will replace nameof(TestClass.Name) with "Name". The fact that it's non-static is irrelevant.

like image 165
D Stanley Avatar answered Oct 12 '22 13:10

D Stanley


nameof Interpreter gets resolved at compiletime and translated to a static string instead.
In your case nameof(TestClass.Name) you will only return "Name" as a string.
You have to use nameof(TestClass).
With nameof you can minimize redundancy in your code (For instance: you dont have to define a string for a propertyname or something like this by using nameof.

You can also use it to represent a classes name. But be aware! nameof(MyClass)
may not be the same as at runtime if you have an derived class! For runtime purposes use typeOf or .GetType() instead.

Read more at MSDN

like image 34
Cadburry Avatar answered Oct 12 '22 12:10

Cadburry