0

I've searched (maybe not enough) but couldn't find an answer.

I want to make a generic function where I can pass any enum to use with a CheckedListBox (get or set the value).

public enum TypeFlags
{
    None = 0x0,
    //List of flag
}

private void makeFlagOrBitmask(CheckedListBox list, Type e)
{
    int myFlags = 0x0;

    //I want to achieve something like that
    foreach (Object item in list.CheckedItems)
    {
        //(TypeFlags)Enum.Parse(typeof(TypeFlags), item);
        //So e should be the enum himself, but i can't figure how to do that
        myFlags += (int)((e)Enum.Parse(typeof(e), item.tostring()));
    }
}

So, I can make/read any flags with a single function.

The problem is that I can't figure out how to pass the enum as I need it in the function.

reformed
  • 4,505
  • 11
  • 62
  • 88
  • Remove typeof(e) and leave Enum.Parse(e... As e is already a type? – Andez Aug 02 '16 at 14:13
  • `typeof(e)` when `e` is `Type` is just going to give you type object for `Type`, not the enum type. You want to just pass `e` to `Enum.Parse`. – juharr Aug 02 '16 at 14:14
  • 2
    Possible duplicate of [Create Generic method constraining T to an Enum](http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum) – Gilad Green Aug 02 '16 at 14:16
  • Yep, i want to rush everything as always and i don't think enough. Thanks guys =) – Nicolas Viseur Aug 02 '16 at 14:18

3 Answers3

0

might not be complete but it sounds like you need a generic Enum iterator. I picked up the below code from Create Generic method constraining T to an Enum

public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) 
   {
      throw new ArgumentException("T must be an enumerated type");
   }

   //...
}
Community
  • 1
  • 1
Ziaullah Khan
  • 2,020
  • 17
  • 20
0

I know this is not a nice Code but this works for me:

If the method want an object instead of a type (maybe you can do this with a type) you can do it like this:

if (e.GetType() == typeof(ImageType))
    {
        ValueArray = GetEnumArray(ImageType.Bmg);
    }

This way you can check what Enum it es before you do something.

I hope this can help you.

Evosoul
  • 197
  • 1
  • 12
-1

You want to change this line:

myFlags += (int)((e)Enum.Parse(typeof(e), item.tostring()));

Into this:

myFlags += (int)((e)Enum.Parse(e, item.tostring()));

Since e is already a type. As of how to pass the parameter:

makeFlagOrBitmask(myCheckBoxList, typeof(myEnum));

I hope this helps.

EDIT:

To make sure only enums will work, add this to the top of your function:

if (!e.IsEnum)
    return;
MasterXD
  • 804
  • 1
  • 11
  • 18