The enum, what a lovely creature available to us in C#. They help make our code more readable and bug-resistant. They also have some tricks up their sleeves.
Take a sample enum declaration:
public enum Level
{
Unknown = 0,
Low,
Medium,
High
}
If you want a string representation of an enum, you simply use the ToString() method.
Console.WriteLine(Level.Unknown.ToString());
/* output:
Unknown
*/
If you want the numeric value of an enum, cast it to an int. (By default, an enum is an int, though you can specify other numeric values for them.)
int i = (int)Level.Low;
Console.WriteLine(i);
/* output:
1
*/
If you have a string and want to convert it to an enum, use the Enum.Parse() method. Pass the enum type, the string value to parse, and an optional boolean parameter to note if you want the parsing to be case-insensitive. (By default, parsing is case-sensitive.)
Level lvl;
// case-insensitive parsing
lvl = (Level)Enum.Parse(typeof(Level), "medium", true);
Console.WriteLine(i);
/* output:
Medium
*/
// default, case-sensitive parsing
lvl = (Level)Enum.Parse(typeof(Level), "high");
/* throws an exception:
System.ArgumentException: Requested value 'high' was not found.
*/
If you have a numeric value and want to . . .
→ Read More: Everything you ever wanted to know about an enum (well, almost everything)

Recent Comments