Wednesday, January 13, 2010

FlagsAttribute and Loop though enum elements

using System;

enum SingleHue : short
{
Black = 0,
Red = 1,
Green = 2,
Blue = 4
};

// Define an Enum with FlagsAttribute.
[FlagsAttribute]
enum MultiHue : short
{
Black = 0,
Red = 1,
Green = 2,
Blue = 4
};


// Display all possible combinations of values.
for( int val = 0; val <= 8; val++ )
Console.WriteLine( "{0,3} - {1}",
val, ( (SingleHue)val ).ToString( ) );



// Display all possible combinations of values.
// Also display an invalid value.
for( int val = 0; val <= 8; val++ )
Console.WriteLine( "{0,3} - {1}",
val, ( (MultiHue)val ).ToString( ) );



All possible combinations of values of an
Enum without FlagsAttribute:

0 - Black
1 - Red
2 - Green
3 - 3
4 - Blue
5 - 5
6 - 6
7 - 7
8 - 8

All possible combinations of values of an
Enum with FlagsAttribute:

0 - Black
1 - Red
2 - Green
3 - Red, Green
4 - Blue
5 - Red, Blue
6 - Green, Blue
7 - Red, Green, Blue
8 - 8
*/


To loop through a enum type elements:

public enum RelOp
{
Equal,
NotEqual,
LessThan,
LessEqual,
MoreThan,
MoreEqual,
In,
NotIn
}

No comments: