Siveur Westtunger Siveur Westtunger - 1 year ago 48
C# Question

C# : Is there a way to pass an enum as an argument?

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

(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.

Answer Source

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.


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

if (!e.IsEnum)