Tuesday, March 13, 2007

Enumerations in C#

The [Flags] attribute is optional and informs the runtime that the values in the enum can be bit-combined and should be decoded accordingly in the debugger or when outputting text to console. For example:


[Flags]
internal enum Colours { Red = 1, Green = 2, Blue = 4, White = 8 };
private void Test()
{
string [] items = System.Enum.GetNames(typeof(Colours));


// this outputs: Red Green Blue White
foreach (string item in items)
textBox1.Text += item + " ";

textBox1.Text += "\r\n";

Colours c = Colours.Red Colours.Blue;


// this outputs: Red, Blue
textBox1.Text += c + "\r\n";

// this outputs: 5
textBox1.Text += (int)n + "\r\n";

}

No comments: