.Net - Detect if desired identifier is a keyword
-
03-07-2019 - |
Question
Is there a way, in .net, to detect if a word is a keyword in a given .net language?
I am using a fairly simple code generator for this project, and I would like to start automating it. Right now I do each one by hand, so fixing any issues that arise is pretty easy. However, once this starts happening automatically I am going to need a way to detect if a word I need to use as an identifier is a keyword. I can still use it, I just need to quote it properly.
I know that I can simply quote everything I generate, but I would like to keep the generated code pretty :)
An example of the kind of things I need to quote:
vb: Public [Class] As String = "CLASS"
c#: public String @class = "CLASS";
Solution
Perhaps you're looking for IsValidIdentifier
[
IsValidIdentifier
] return[s] true only if the value fits the rules of the language and does not conflict with a keyword.
CreateEscapedIdentifier
tests whether the identifier conflicts with any reserved or language keywords, and if so, returns an equivalent name with language-specific escape code formatting
For example:
CSharpCodeProvider csProvider = new CSharpCodeProvider();
bool isValid1 = csProvider.IsValidIdentifier("class");
// returns false
string escapedId1 = csProvider.CreateEscapedIdentifier("foo");
// escapedId1 = "foo"
string escapedId2 = csProvider.CreateEscapedIdentifier("do");
// escapedId2 = "@do"
string escapedId3 = csProvider.CreateEscapedIdentifier("AndAlso");
// escapedId3 = "AndAlso" (not reserved in c#)
VBCodeProvider vbProvider = new VBCodeProvider();
string escapedId4 = vbProvider.CreateEscapedIdentifier("AndAlso");
// escapedId4 = "[AndAlso]" (reserved in VB)
Seems like it wouldn't be too hard to extend/use this facility to meet your needs.