I had to write a switch case for an Enum that contains huge amount of members. Writing each case with hitting the keyword is frustrating and time consuming. So I wrote a little code that builds a switch case for every member of Enum in an Assembly.
The Logic behind the scene is extremely simple. What one need to do is.
-
load an assembly
- Enumerate all Enum types from the loaded assembly.
- Build the switch case
Load and Enumerat all Enums from an assembly and store it in a combo box
private void LoadAsm(String Path)
{
/*Load an Assembly*/
Assembly asm = Assembly.LoadFile(Path);
if (asm != null)
{
Type[] tp = asm.GetTypes();
foreach (Type t in tp)
{
/*If type is Enum add it to tne combobox*/
if (t.IsEnum && t.BaseType == typeof(Enum))
{
this.comboBox1.Items.Add(t);
}
}
}
}
Now, All enums are loaded into combobox. Time to build the switch case
private void BuildSwitch()
{
Type t = this.comboBox1.SelectedItem as Type;
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format(“{0} Enm;”, t.Name));
sb.AppendLine(“switch(Enm)”);
sb.AppendLine(“{“);
/*Prepare case for each name of the enum*/
foreach (string str in Enum.GetNames(t))
{
sb.AppendLine(string.Format(“case {0}.{1}:”, t.Name,str));
sb.AppendLine(“break;”);
}
sb.AppendLine(“}”);
this.richTextBox1.Text = sb.ToString();
}
Filed under: C# Tagged: | C#, Reflection



Great Article thanks. Might be useful.