Dynamically generate ENUMs through assembly

Share

In C# ENUMs are storage efficient data structure acting at run-time just like primitive types. The following presents one way to generate an enumeration class within a dynamic assembly using database data.

Let’s assume we have the following table and we want to map this to an enum type:
—————-
id | description
—————-
0 | pink
1 | magenta
—————-

First will retrieve the data constructing the enum source code into a string variable. For data access we use a SQL helper class that loads a DataReader object.
One thing we have to check here is to remove not allowed characters from the enumeration names list. Also values must be integer numbers.

            string strEnumSource = "enum colors {";
            OracleDataReader rdr = Sql.ExecuteReader("SELECT id, description FROM colors");
 
            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    int nValue;
                    string strKey;
 
                    strKey = Convert.ToString(rdr[1]);
                    strKey = Regex.Replace(strKey, @"[^\w\.@-]", "");
                    if (!Int32.TryParse(Convert.ToString(rdr[0]), out nValue))
                        throw new Exception("ERROR: value must be an integer!");
                    strEnumSource += strKey + "=" + nValue + ",";
                }
            }
            if (strEnumSource.EndsWith(","))
                strEnumSource = strEnumSource.Remove(strEnumSource.LastIndexOf(","));
            strEnumSource += "}";

Next will compile the enum using the CodeDomProvider abstract class. A CodeDomProvider implementation provides an interface for generating code and managing compilation for a single programming language.

  CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

We don’t want to save anything to disk so will use a CompilerParameters object to specify the compiler settings.

  CompilerParameters cparam = new CompilerParameters();
 
  cparam.GenerateExecutable = false;
  cparam.GenerateInMemory = true;
  cparam.TreatWarningsAsErrors = false;
 
  CompilerResults cresult = codeProvider.CompileAssemblyFromSource(cparam, strEnumSource);

The Errors property of the CompilerResults class exposes the messages resulting from compilation, if any.

                    if (cresult.Errors.Count > 0)
                    {
                        foreach (CompilerError ce in cresult.Errors)
                            strErrors += ce.ToString() + System.Environment.NewLine;
                        throw new Exception("ERROR: " + strErrors);
                    }

If there are no compilation errors we can simply get the type compiled and ready for use.

  Type enumType = cresult.CompiledAssembly.GetType("colors");
  int[] nValues = (int[])Enum.GetValues(enumType);
  string str = "";
 
  foreach (int nValue in nValues)
    str += String.Format(" {0}: {1} ", Enum.GetName(enumType, nValue), nValue);

Namespace: System.CodeDom.Compiler

Finally, there’s another very important peculiarity of what does Cialis that brings it so high above its alternatives. It is the only med that is available in two versions – one intended for use on as-needed basis and one intended for daily use. As you might know, Viagra and Levitra only come in the latter of these two forms and should be consumed shortly before expected sexual activity to ensure best effect. Daily Cialis, in its turn, contains low doses of Tadalafil, which allows to build its concentration up in your system gradually over time and maintain it on acceptable levels, which, consequently, makes it possible for you to enjoy sex at any moment without having to time it.

2 thoughts on “Dynamically generate ENUMs through assembly”

Comments are closed.

By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close