středa 10. listopadu 2010

CSharpCodeProvider.CreateEscapedIdentifier() is it good for anything?

Mkay, so I have an extended T4 template for Entity Framework. One of the things it does is generating enums out of a few marked tables. I mark the table in the Designer and specify the column to use for the enum item names, the values are taken from the primary key. The template then connects to the database, fetches the data from those (static loookup) tables and generates the enums. And I use the code.Escape(name) that the original template uses all over the place to escape the names of the entities and properties. So I am safe right? The options will not be exactly the same as the values in the database, because they have to be valid identifiers, but what the heck. We have intellisense.

The code.Escape() calls CSharpCodeProvider.CreateEscapedIdentifier() which does ... well nothing really. If the string contains a space, the result will contain a space. If it contains a dash, the result will contain a dash. Etc. etc. etc.
So far it seems the only thing it does is ... if the whole string matches a C# keyword, the method prepends @.

OK, let's see the docs.

Public methodCreateEscapedIdentifierCreates an escaped identifier for the specified value. (Inherited from CodeDomProvider.)
Yeah, sure.
Any other candidates?

Public methodCreateValidIdentifierCreates a valid identifier for the specified value. (Inherited from CodeDomProvider.)
OK, let's try ... nope. Seems the only difference is that instead of @ we get an underscore. But just like the CreateEscapedIdentifier()
code.CreateValidIdentifier("Hello world") == "Hello world"

How's that a valid identifier I really do not know.
Funny thing is that code.IsValidIdentifier("Hello world") returns false. Just like code.IsValidIdentifier(code.CreateValidIdentifier("Hello world")) of course.

Thank you very much Microsoft once again!

Žádné komentáře: