Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "nameof " operator,"expression cannot be used in an argument to nameof"

Tags:

c#

c#-6.0

I got a simple class:

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

If I do like this:

var stu = new Stu();
Console.WriteLine(nameof(stu.Name));

it works well. but this:

Console.WriteLine(nameof(new Stu().Name));

or this:

Console.WriteLine(nameof((new Stu()).Name));

not work,the complier tells me :"expression cannot be used in an argument to nameof".

I don't know why.What the tip means for?What is the corret parameter type of the operator "nameof()"?

I searched the web,this page tells me the "expression may be a property-group or a method-group",but is the expression "new Stu().Name" not a "property-group"?

like image 603
eforlina Avatar asked Jul 16 '15 02:07

eforlina


People also ask

What is Nameof operator?

The nameof operator accepts the name of code elements and returns a string literal of the same element. The parameters that the nameof operator can take can be a class name and all its members like methods, variables and constants and returns the string literal.

What is Nameof used for?

C# NameOf operator is used to get name of a variable, class or method. It returns a simple string as a result. In error prone code, it is useful to capture a method name, in which error occurred. We can use it for logging, validating parameters, checking events etc.

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.

Is Nameof reflection?

Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!


1 Answers

You probably want

nameof(Stu.Name)

nameof() gets some special syntax so you don't have to instantiate a class to get the name of one of its properties, and other similar scenarios.

like image 71
Nick Strupat Avatar answered Oct 10 '22 12:10

Nick Strupat