C# enums as function parameters?

TK. picture TK. · Jan 29, 2009 · Viewed 46.6k times · Source

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?

Answer

Daniel Schaffer picture Daniel Schaffer · Jan 29, 2009

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.