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?
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));
}
David: I'm trying to emulate Dwarf Fortress on a smaller scale. You can change all sorts of stuff via some kind of flat text files that the game parses through on startup. Not sure how exactly they have it set up, although my guess is that if you have to hardcode Enums to work with them, then it wouldn't be with them - Kyle Baran 2012-04-05 00:54
You could also do this with a generic method. Personally I like the syntax better for the foo()
method this way, since you don't have to specify typeof()
// 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>();
}