Search code examples
c#enumsfunction-parameter

c# Enum Function Parameters


As a follow on from this question.

How can I call a function and pass in an Enum?

For example I have the following code:

enum e1
{
    //...
}

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

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

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

}

Although when I do this I am getting the 'e1' is a 'type' but is used like a 'variable' Error message. Any ideas to help?

I am trying to keep the function generic to work on any Enum not just a specific type? Is this even possible?... How about using a generic function? would this work?


Solution

  • You can use a generic function:

        public void myFunc<T>()
        {
            var names = Enum.GetNames(typeof(T));
    
            foreach (var name in names)
            {
                // do something!
            }
        }
    

    and call like:

        myFunc<e1>();
    

    (EDIT)

    The compiler complains if you try to constraint T to Enum or enum.

    So, to ensure type safety, you can change your function to:

        public static void myFunc<T>()
        {
            Type t = typeof(T);
            if (!t.IsEnum)
                throw new InvalidOperationException("Type is not Enum");
    
            var names = Enum.GetNames(t);
            foreach (var name in names)
            {
                // do something!
            }
        }