Passing an Enum as an argument

I am playing around trying to make a simple Roguelike game to learn a little C #. I'm trying to make a generic method so that I can give it an Enum as an argument and it will return the number of elements in that Enum as an int. I need to make this as general as possible because I will have multiple classes calling the method.

I've searched around for the last hour or so, but I couldn't find any resources here or otherwise, which quite answered my question ... I'm still in the early stages for C #, so I'm still learning all the syntax for things but here is what I have so far:

// Type of element
public enum ELEMENT
{
    FIRE, WATER, AIR, EARTH
}


// Counts how many different members exist in the enum type
public int countElements(Enum e)
{
    return Enum.GetNames(e.GetType()).Length;
}


// Call above function
public void foo()
{
    int num = countElements(ELEMENT);
}

      

It compiles with the error "Argument 1: Cannot convert from" System.Type "to" System.Enum ". I can somehow understand why this won't work, but I just need some direction to get things set up correctly.

Thank!

PS: Is it possible to change the contents of an enum at runtime? During program execution?

+3


source to share


2 answers


Try the following:



public int countElements(Type type)
{
    if (!type.IsEnum)
        throw new InvalidOperationException();

    return Enum.GetNames(type).Length;
}

public void foo()
{
    int num = countElements(typeof(ELEMENT));
}

      

+7


source


You can also do this with a generic method. Personally, I like the syntax for the method better foo()

since you don't need to specifytypeof()



    // Counts how many different members exist in the enum type
    public int countElements<T>()
    {
        if(!typeof(T).IsEnum)
            throw new InvalidOperationException("T must be an Enum");
        return Enum.GetNames(typeof(T)).Length;
    }

    // Call above function
    public void foo()
    {
        int num = countElements<ELEMENT>();
    }

      

+3


source







All Articles