How to validate correct Enum name?

Based upon content in a code table in a database, I want generate an enumeration. However, the code table could contain names that are not valid enum names. Is there a function or a way to "convert" and check these names in order to generate a properer enumeration name.

For example, the HumanResources.Department table of the AdventureWorks sample database contains "Engineering" (=ok) and "Tool Design" (=nok).



Answer this question

How to validate correct Enum name?

  • Mirek Smolinski

    I think I did not explain very good what I'm actually looking for...

    When I generate code based upon entries in a database, I want to make sure that the text is in compliance with restrictions of a type in an enumerator. That means for example, I cannot use spaces, cannot start with a numeric value, etc.

    I'm looking for an easy way to convert my string value in the database towards a valid value in the output code generation.


  • tom-taker

    Enum.IsDefined will tell you whether a constant or name is valid for the given enumeration. However as with all Enum methods it uses reflection and will be slow. I personally create a helper static class for each enumeration I create (that is public) that supports Parse() and ToString(). At a cost of additional maintenance it gives me better performance and reduces the complexity of the call from:

    Enum.IsDefined(typeof(MyType), "someName");
    MyTypeval = (MyType)Enum.Parse(typeof(MyType), "someName");

    to

    class MyTypeHelper
    {
    public MyType Parse ( string name )
    {
    switch(name)
    {
    ...
    };
    }
    }

    The above method also lets me match multiple names to the same value. For example in a database I might want to support: Tools, Tools Design and Tool Design for the same enumeration.

    Michael Taylor - 1/23/06


  • bodhi147

    Ah, even easier. Enumeration names, like all identifiers, must meet the CLS requirements. I believe the rules are as follows:

    • Must begin with a letter or underscore
    • Can consist of the following:
      • letters
      • digits
      • underscores
      • variety of unicode characters

    I'm not aware of a method to take a string and figure it out but a simple regular expression would work. I'd personally just strip out the spaces and permit letters, digits and underscores only.

    Michael Taylor - 1/23/06


  • How to validate correct Enum name?