Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#
Article

Enums powered by Reflection

Rate me:
Please Sign up or sign in to vote.
2.93/5 (14 votes)
25 Apr 20032 min read 95.2K   865   25   8
An article about building enums in runtime by means of System.Reflection.Emit

Sample Image - enumsReflection.jpg

Introduction

C# enums are a quite powerful element of the C# language. Because of its metadata stored in the assembly they provide us with much more info than their equivalent in C++. What´s more, using System.Reflection.Emit we can delay the creation of an enum till runtime.

Using the code

In C# (as in C++) every instance of an enum type takes 4 bytes in memory (only the integer value associated to the string value is stored), you can use sizeof to verify this, so it´s a really storage efficient data structure. The great thing in C# is that for every enum class in our code the string values are stored in the assembly as metadata, so we can access to it in our code. We can use for it methods like Enum.GetNames(). Here´s a little sample:

C#
enum Language
{
    CSharp,MCpp,VBNet,JScript,IL
}
class App
{
    public static void Main()
    {
        Console.WriteLine("Write the number of the selected Language");
        string[] langAr=Enum.GetNames(Type.GetType("Language"));
        for(int i=0;i<langAr.Length;i++)
        {
            Console.WriteLine(i + "." + langAr[i]);
        }
        Language myLang=(Language)Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Your Language of choice is: " + myLang);
    }
}
Another great thing about C# enums is that we can create an enum class in runtime, after the users have fed our program with data. In the following sample we want an enum with the months that our business offers to our employees to choose as holidays month. The problem is that we don´t know till runtime which months we are going to offer to our employees. System.Reflection.Emit comes in our help. First we fill a string with the source code for the new enum (Holidays), then we write it to disk and compile it. Finally we load the new assembly. Since that moment we can work with the new enum we´ve coded, and we can create instances of that new enum. One useful method we need to assign values to the instances of our new enum class is Enum.parse Here it´s how it works:
C#
Employee emp=new Employee();
Console.WriteLine("Insert Employee data");
Console.WriteLine("Name");
emp.Name=Console.ReadLine();
Console.WriteLine("HolidayMonth");
string hm=Console.ReadLine();
//Create an instance of our dynamic enum (Holidays)
emp.HolidayMonth=(Enum)(a.CreateInstance("Holidays"));
try
{
    //assign the right value to the enum instance
    emp.HolidayMonth=(Enum)(Enum.Parse(emp.HolidayMonth.GetType(),hm));
}
For this sample I make use of a small, incomplete and untested Library (ReflectiveTools) that I´ve coded to make easier some of the most common reflection operations (saving dynamic code to disk and compiling it). This library is included in the zip file. Well, I think you have to download the source code to really understand the purpose of this article.

Conclusion

I hope this article to be an example of how useful C# enums can be.

I really can´t understand why languages like Java have excluded enums of the language. One last thing, some of the comments in the source code are written in Spanish, I´m sorry, but that´s my native language. Anyway I don´t think those comments are too important.

 

History

  • 04/04/2003: This article is submitted to CodeProject

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Spain Spain
My name is Jose Luis Sampayo Aller, I´m from Xixón-Asturies-Spain.
I´ve got a degree in Computer Science by University of Oviedo.
I´ve been having fun with .Net since April 2002.
My main current interests are: .Net and Mono, OOP (mainly C# and C++), IA-32 assembler (hope someday I´ll learn it), OS Internals (mainly Nt family). Outside computer world I´m really interested in Neuroscience, Science in general, Science Fiction...

Comments and Discussions

 
Generalcan't read enum in other assembly using reflection Pin
Do.It5-Jul-07 21:50
Do.It5-Jul-07 21:50 
AnswerRe: can't read enum in other assembly using reflection Pin
LazyTarget15-May-13 7:37
LazyTarget15-May-13 7:37 
GeneralGood article but I have a question Pin
mrsnipey11-Sep-06 0:12
mrsnipey11-Sep-06 0:12 
GeneralDynamic Enums without writing to file Pin
nlgarvey21-Jun-06 4:59
nlgarvey21-Jun-06 4:59 
GeneralItem count Pin
AlainT21-Sep-05 4:33
AlainT21-Sep-05 4:33 
Generalsimple to understand but example could be better Pin
dog_spawn26-Apr-03 12:51
dog_spawn26-Apr-03 12:51 
GeneralRe: simple to understand but example could be better Pin
Lennin9-Nov-03 23:55
Lennin9-Nov-03 23:55 
GeneralEnums can be 1, 2, 4, or 8 bytes long Pin
Wesner Moise26-Apr-03 11:07
Wesner Moise26-Apr-03 11:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.