Dino Esposito did a writeup over at MSDN on enumeration types. I was about to dismiss it, but then I realized that I don’t really use them in my code, so I should probably review them. Sure enough, I leaned a few things, particularly around using them as bitfields via the Flags attribute:
1 [Flags]
2 enum Foods : int
3 {
4 apples = 1,
5 pears = 2,
6 oranges = 4,
7 bananas = 8,
8 beans = 16
9 }
10
11 static void Main(string[] args)
12 {
13 Foods foods = Foods.apples | Foods.bananas;
14 Console.WriteLine(Enum.Format(typeof(Foods), foods, “g”));
15 Console.ReadLine();
16 }
That outputs “apples, bananas” which is a handy way out of writing an output loop with comma separators, but is kind of useless. Where it gets handy is the Parse operator, which can take “apples, bananas” from a string, say, for instance, a config string, and make it into a variable. Nice.
1 static void Main(string[] args)
2 {
3 Foods myFoods = (Foods)Enum.Parse(typeof(Foods), “pears, beans, oranges”);
4 Console.WriteLine(Enum.Format(typeof(Foods), myFoods, “g”));
5 Console.ReadLine();
6 }
Post a Comment