19

Possible Duplicate:
C# enums as function parameters?

I was wondering how I can pass an enum type as a method argument.

I'm trying to create a generic method that will take a combo box, and enum, and fill the combo box with each item of the enum.

Community
  • 1
  • 1
sooprise
  • 22,657
  • 67
  • 188
  • 276

6 Answers6

19

I think this is best explained by an example:

Say you have an enum:

enum MyEnum
{
    One,
    Two,
    Three
}

You can declare a method like:

    public static void MyEnumMethod(Enum e)
    {
        var enumValues = Enum.GetValues(e.GetType());

        // you can iterate over enumValues with foreach
    }

And you would call it like so:

MyEnumMethod(new MyEnum());
cbley
  • 1,695
  • 12
  • 8
14

Refering to Convert Enum To Dictionary:

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>()
{
 if (typeof(K).BaseType != typeof(Enum))
 {
   throw new InvalidCastException();
 }

 return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
}

Then you can fill your ComboBox with the returned dictionary items.

Refer to the following as well:

Dictionary enumeration in C#

Enum to dictionary

Community
  • 1
  • 1
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
8

You can pass an enum generically like this:

private void Method(Enum tEnum)
{
    Enum.GetValues(tEnum.GetType());
}

And the GetValues will give you the values that are possible for that enum.

Usage would be a little odd:

Method(EnumType.Value)

so it might not fit as well as other ideas.

Rangoric
  • 2,739
  • 1
  • 18
  • 18
5

Using this method, you cann add any type of enum like this: AddItems(myCombobox, typeof(Options))

  public void AddItems (ComboBox cboBox, Type enumType)
  {
     cboBox.Items.AddRange(Enum.GetValues (enumType).Cast<object> ().ToArray ());
  }

  enum Options
  {
     Left, Right, Center
  }
agent-j
  • 27,335
  • 5
  • 52
  • 79
2

You can use:

Enum.GetValues(typeof(MyEnumType))

and just populate the combo box items from that

Edit: and of course use reflection to get the enum type :)

Franchesca
  • 1,453
  • 17
  • 32
0

you could maybe use a kind of generic enum helper like here : http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx.

Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73