Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22814

Create enum using reflection

Does C# offer a way to create Enum type from scratch using reflection?

Suppose, I have a collection of strings: {"Single", "Married", "Divorced"} and I'm willing to build the following enum type in runtime:

enum PersonStatus
{
    Single, Married, Divorced
}

Is this somehow possible?

Upvotes: 5

Views: 4237

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Does C# offer a way to create Enum type from scratch using reflection?

Yes, it's possible. If you want to create types (including enums) at runtime you could use Reflection.Emit in order to emit the actual MSIL code.

Here's a concrete example of how to achieve that using the DefineEnum method.

Upvotes: 9

Chris Shain
Chris Shain

Reputation: 51319

Not without doing really gnarly things like generating assemblies using Emit. How would you use such an enum anyway? Whats the real goal here?

EDIT: Now that we know what you really want to do, this page suggests that you can acheive your goal using code like the following:

private void listViewComplex_CellEditStarting(object sender, CellEditEventArgs e)
{
    // Ignore edit events for other columns
    if (e.Column != this.columnThatYouWantToEdit)
        return;

    ComboBox cb = new ComboBox();
    cb.Bounds = e.CellBounds;
    cb.Font = ((ObjectListView)sender).Font;
    cb.DropDownStyle = ComboBoxStyle.DropDownList;
    cb.Items.AddRange(new String[] { "Single", "Married", "Divorced" });
    cb.SelectedIndex = 0; // should select the entry that reflects the current value
    e.Control = cb;
}

Upvotes: 8

Related Questions