21

Can you pass a standard c# enum as a parameter?

For example:

enum e1
{
    //...
}

enum e2
{
    //...
}

public void test()
{
    myFunc( e1 );
    myFunc( e2 );
}

public void myFunc( Enum e )
{
    // Iterate through all the values in e
}

By doing this I hope to retrieve all the names within any given enum. What would the Iteration code look like?

7 Answers 7

30

This!

        public void Foo(Enum e)
        {
            var names = Enum.GetNames(e.GetType());

            foreach (var name in names)
            {
                // do something!
            }
        }   

EDIT: My bad, you did say iterate.

Note: I know I could just do the GetNames() call in my foreach statement, but I prefer to assign that type of thing to a method call first, as it's handy for debugging.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd probably assign the result to something. :-)
yeah whups... sorry, I got excited :D
3

Use the Enum.GetNames( typeof(e) ) method, this will return an array of strings with the names.

You can also use Enum.GetValues to obtain the counterpart values.

Edit -Whoops - if you are passing the parameter as Enum, you will need to use e.GetType() instead of typeof() which you would use if you had passed the parameter in as the actual Enum type name.

Comments

3

You mean something like Enum.GetNames?

Comments

3

Enum.GetValues Enum.GetNames

so something like...

foreach(e1 value in Enum.GetValues(typeof(e1)))

Comments

3

You will have trouble if you try passing an enum directly to myFunc, as in the following example:

enum e1 {something, other};
myFunc(e1);  // Syntax error: "e1 is a type, but is being used like a variable"

2 Comments

That doesn't explain anything, in fact I have no issue passing an enum to a function in the way you describe...
Error: 'e1' is a 'type' but is used like a 'variable'
2

Like this:

    public void myFunc(Enum e)
    {
        foreach (var name in Enum.GetNames(typeof(e)))
        {
            Console.WriteLine(name);
        }
    }

Comments

1

correct is:

public void myFunc(Enum e)
{
    foreach (var name in Enum.GetNames(e.GetTye()))
    {
        Console.WriteLine(name);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.