52

I regularly want to get the name of an instance property of a type, when I have no instance. Currently to do this, I use the following inhouse function which interprets the Expression[Func[T, object]] parameter and returns the property name:

var str = LinqExtensions.NameOf<ClientService>(x => x.EndDate);
// Now str == "EndDate"

However it seems a shame not to use the built in nameof operator.

Unfortunately it seems that the nameof operator requires either an instance, or, to reference a static properties.

Is there a neat way to use the nameof operator instead of our in house function? For example:

nameof(ClientService.EndDate) // ClientService.EndDate not normally syntactically valid as EndDate is instance member

EDIT

I was completely wrong, the syntax nameof(ClientService.EndDate) as described actually works as is.

1
  • Can you post your in-house function? <_<
    – Pangamma
    Commented Jun 16, 2021 at 20:06

2 Answers 2

66

In the past, the documentation explicitly explained this, reading in part:

In the examples you see that you can use a type name and access an instance method name. You do not need to have an instance of the type[emphasis mine]

This has been omitted in the current documentation. However, the examples still make this clear. Code samples such as Console.WriteLine(nameof(List<int>.Count)); // output: Count and Console.WriteLine(nameof(List<int>.Add)); // output: Add show how to use nameof to obtain the string value with the name of an instance member of a class.

I.e. you should be able to write nameof(ClientService.EndDate) and have it work, contrary to your observation in the question that this would be "not normally syntactically valid".

If you are having trouble with the syntax, please provide a good Minimal, Complete, and Verifiable code example that reliably reproduces whatever error you're getting, and provide the exact text of the error message.

1
  • 5
    The syntax of nameof(MyClass.PublicProperty) is still valid. It evaluates as "PublicProperty". It is not being offered by Intellisense, but writing it manually compiles allright. Commented Aug 25, 2021 at 8:25
6

Great answer by @Peter Duniho.

In case of name clashes, you can also do the following:

ClientService clientservice;
var str = nameof(clientservice.EndDate);

Not efficient, but curious enough.

3
  • 1
    in the case of name clashes, then both nameofs resolve to the same text, so it may not matter Commented May 13, 2020 at 10:12
  • 1
    @AndrewHill that's a bad idea because half the reason to use nameof is so that doing IDE refactors (rename variable) doesn't get missed in literal strings somewhere, by doing a nameof on a different class you're reintroducing that chance again.
    – Issung
    Commented Mar 18, 2021 at 3:56
  • I got code inspection notice "Local variable its only used to capture its name" Commented Apr 17, 2021 at 15:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.