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"?
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.
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.
The nameof operator, added in C# 6.0, addresses this — it allows capturing the string names of symbols that are in the scope.
Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With