I want to create a dynamic GUI that lists all of an Enum's options as buttons. So, I need a way to pass an Enum type to a method and get back a string array of all the options that enum type can be.
For example, given an Enum declaration in the file Foo.cs:
public Enum Fruits {
Apple,
Orange,
Peach
};
public class Foo { ... }
I want this returned:
{ "Apple", "Orange", "Peach" }
I have gone through several permutations of code. Right now I have the following but I am getting an error " Type or namespace name 'enumeratedType' cannot be found "
public static string[] EnumToStringArray (System.Type enumeratedType) {
int enumSize = sizeof(enumeratedType);
string[] enumStrings = new string[enumSize];
for (int i = 0 ; i < enumSize ; i++) {
enumStrings[i] = enumeratedType.getValues()[i].toString();
}
return enumStrings;
}
Is what I am trying to do possible? I have tried several complete rewrites based on information in this question Using sentinal values in C# enum (size of enum at compile time)? but I couldn't get it to work.
string[] names = Enum.GetNames(typeof(Fruits));
You could use something like
public static IEnumerable<string> EnumToStringArray(Type enumeratedType) {
if (!enumeratedType.IsEnum)
throw new ArgumentException("Must be an Enum", "enumeratedType");
return Enum.GetNames(enumeratedType);
}
but even that is needless, since Enum.GetNames(...)
itself throws an ArgumentException
if the given type is no Enum
. (Thanks @Alexander Balte). So you don't need an own function anyway. Simply Enum.GetNames(typeof(Fruits))
does the job, as others already mentioned.
You seem to have misunderstood the meaning of the sizeof
keyword . It returns the number of bytes (each byte equals 8 bits) that the value type "takes up" when it's lined up with other values in unmanaged memory.
sizeof
is not useful if you don't use unsafe
context (like pointers).
For your Fruits
type, sizeof(Fruits)
returns 4
since the underlying iteger type is an Int32
(because that's the default when you don't specify otherwise). An Int32
requires 32 bits, therefore sizeof
returns 4
. It doesn't matter if you have 1, 2, 10, or 4294967296 different fruits.
Note that an enum can have multiple names pointing to the same value, like:
public enum Fruits {
Apple,
Orange,
Peach,
ChineseApple = Orange,
}
In this example, the enum contains four named constants, but two of them "map to" the same value. In that case, Enum.GetNames(typeof(Fruits))
, will give you all four names.
But Enum.GetValues(typeof(Fruit))
will give you a list of four values of Fruit
, two of which are identical. You can't know in advance if the two identical values will be displayed as Orange
or ChineseApple
, so don't use this approach if your enum has duplicates like that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.