views:

473

answers:

2

I'm looking for a quick way (in C#) to determine if a string is a valid variable name. My first intuition is to whip up some regex to do it, but I'm wondering if there's a better way to do it. Like maybe some kind of a secret method hidden deep somewhere called IsThisAValidVariableName(string name), or some other slick way to do it that is not prone to errors that might arise due to lack of regex prowess.

+13  A: 

Try this:

// using System.CodeDom.Compiler;
CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
if (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) {
      // Valid
} else {
      // Not valid
}
Gonzalo
You need to reference the `System.CodeDom.Compiler` namespace for that :-)
CesarGon
Yes. You also need to put that code inside a method, and the method in a class and a variable named YOUR_VARIABLE_NAME and... ;-)
Gonzalo
How expensive is a `CodeDomProvider`?
Loadmaster
Okayyyyy..............
CesarGon
@Loadmaster: I think only CreateProvider will be 'expensive' (it reads from configuration files). Everything else is 'cheap'.
Gonzalo
That's what I meant: how much overhead is needed to instantiate `provider`?
Loadmaster
A: 

The longer way, plus it is much slower, is to use reflection to iterate over members of a class/namespace and compare by checking if the reflected member**.ToString()** is the same as the string input, this requires having the assembly loaded beforehand.

Another way of doing it (a much longer way round it that overcomes the use of regex, by using an already available Antlr scanner/parser) borders on parsing/lexing C# code and then scanning for member names (i.e. variables) and comparing to the string used as an input, for example, input a string called 'fooBar', then specify the source (such as assembly or C# code) and scan it by analyzing looking specifically for declaration of members such as for example

private int fooBar;

Yes, it is complex but a powerful understanding will arise when you realize what compiler writers are doing and will enhance your knowledge of the C# language to a level where you get quite intimate with the syntax and its peculiarities.

Hope this helps, Best regards, Tom.

tommieb75