c# Enum Function Parameters

14,299

Solution 1

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!
        }
    }

Solution 2

Why not passing the type? like:

 myfunc(typeof(e1));

public void myFunc( Type t )
{
}

Solution 3

You are trying to pass the type of the enum as an instance of that type - try something like this:

enum e1
{
    foo, bar
}

public void test()
{
    myFunc(e1.foo); // this needs to be e1.foo or e1.bar - not e1 itself
}

public void myFunc(Enum e)
{
    foreach (string item in Enum.GetNames(e.GetType()))
    {
        // Print values
    }
}
Share:
14,299
TK.
Author by

TK.

--

Updated on July 28, 2022

Comments

  • TK.
    TK. almost 2 years

    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?

  • TK.
    TK. over 15 years
    I am aware that I canpass individual values like this. I am looking to pass a generic Enum to a function to say print all the values not just one.
  • TK.
    TK. over 15 years
    if I use "if ( e is Enum )" or the 'as' statement, then I get an error "Cannot convert type 'System.Type' to 'System.Enum' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"
  • TK.
    TK. over 15 years
    I was trying to keep the function generic to work on any Enum not just a specific type?
  • Jon B
    Jon B over 15 years
    This will print all the values. Use Enum.GetNames(e.GetType()).
  • TK.
    TK. over 15 years
    How could I type-safe this to ensure that ony enums are used instead of any type?
  • Andy
    Andy over 15 years
    Use typeof(Enum).IsAssignableFrom(t) - that will return false of t does not represent an Enum type.