So what I am trying to do is quite simple.
I am trying to run a nameof()
on some of the primitive types as I need these constants for a certain requirement.
But when I try to do that for eg nameof(bool)
it says that nameof()
does not exist in the current context.
And this seems to be the case with all Synonyms?
Is there any other way to do this or am I missing something.
what I am trying to do is
public static readonly string BoolConstant= nameof(bool);
Expected result:
BoolConstant= "bool";
Will I have to write all these constants down?
nameof
is only applicable to Type and its members and not the keywords, bool
is keyword, basically bool is short for Boolean
.
Try nameof(Boolean)
, it works.
As per MS Documentation,
nameof_expression
: 'nameof' '(' named_entity ')'
;
named_entity
: simple_name
| named_entity_target '.' identifier type_argument_list?
;
named_entity_target
: 'this'
| 'base'
| named_entity
| predefined_type
| qualified_alias_member
;
named_entity
can be simple_name
, and simple_name
can be identifier with type argument list, nowhere in this Grammar it says that named_entity
can be predefined_type
, int, bool
etc fall under predefined_type
.
So as per this grammar,
nameof(this)
is not acceptable, but nameof(this.Property)
is, same way no keywords can be used inside nameof(..)
. I don't know the reason but it seems unnecessary and also it would make compiler more complicated to distinguish between grammar that uses keywords.
nameof
itself is also a keyword
List of keywords in C# https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/