1

I am using CreateProvider() to check if a string is good variable name.

var codeDomProvider =   CodeDomProvider.CreateProvider("C#");
var goodName        =   codeDomProvider.CreateValidIdentifier("ab.cd");

surprisingly, it gives me back 'ab.cd'. Visual Studio never allows such name. how does this happen? I tried again with 'System.Type':

var codeDomProvider =   CodeDomProvider.CreateProvider("C#");
var goodName        =   codeDomProvider.CreateValidIdentifier("System.Type");

it gives me back 'System.Type'. this is troubling.

svick
  • 236,525
  • 50
  • 385
  • 514
CaTx
  • 1,421
  • 4
  • 21
  • 42

1 Answers1

2

The documentation for CreateValidIdentifier() says:

CreateValidIdentifier tests whether the identifier conflicts with reserved or language keywords, and if so, attempts to return a valid identifier name that does not conflict.

So, it's not meant as a general-purpose identifier validation method. I believe it's mostly meant for multi-language environments, where an identifier might conflict with a keyword in one language, but not in others.

I think what you're looking for is IsValidIdentifier():

This method tests whether an identifier is valid.

And for your values, it indeed returns false. This will tell you that an identifier is not valid, but it won't tell you how to fix it, you will have to figure that out yourself. Looking at the source of IsValidIdentifier() might help with that.

svick
  • 236,525
  • 50
  • 385
  • 514