views:

147

answers:

4

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";
+1  A: 

I don't believe there's any natural way to do this programmatically, but you can get a full list of keywords for C# here, and for VB.Net here.

mquander
+2  A: 

See here. Man, Jon Skeet is everywhere!

BFree
+4  A: 

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.

or CreateEscapedIdentifier

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.

Daniel LeCheminant
+2  A: 

Doesn't CodeDOM already take care of this? You could build your generated code that way and automatically get support for any language which supports CodeDOM.

Craig Stuntz