Passing an Enum as an argument
c#, enumeration, parameters, types
Solution
Try this:
public int countElements(Type type)
{
if (!type.IsEnum)
throw new InvalidOperationException();
return Enum.GetNames(type).Length;
}
public void foo()
{
int num = countElements(typeof(ELEMENT));
}
Problem
I am playing around with trying to make a simple Roguelike game to learn C# a bit better. I am trying to make a general method that I can give it an Enum as an argument, and it will return how many elements are in that Enum as an int. I need to make it as general as possible, because I will have several different classes calling the method. I have searched around for the last hour or so, but I couldn't find any resources here or otherwise that quite answered my question... I'm still at a beginner-intermediate stage for C#, so I am 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 kind of see why it won't work but I just need some direction to set everything up correctly. Thanks! PS: Is it possible to change the contents of an enum at runtime? While the program is executing?