How To: Working with Enums in C##

Enums are special value types that lets you specify a group of numeric constants. For example:

enum Languages
{
   English,
   Spanish,
   Chinese,
   Japanese,
   French,
   Filipino
}

We can use an anum as follows:

Languages ls = Languages.Filipino
bool canSpeakFilipino (ls == Languages.Filipino)
//return true

By default enums have an underlying ingtegral value which is of type int and the constant values start from 0 to infinity based on how they enum members are declared. You can also specify an alternate integral type as follows

enum Languages: byte

   English,
   Spanish,
   Chinese,
   Japanese,
   French,
   Filipino
}

Or do an explicit value for each enum member

enum Languages: byte

   English = 1,
   Spanish = 2,
   Chinese = 4,
   Japanese = 8,
   French = 16,
   Filipino = 32
}


You can also assign some values of the enum and let the compiler decide on the value of the other unassigned enum members which is an increment of 1 by the previous value of the previous member.

enum Languages

   English = 1,
   Spanish,
   Chinese,
   Japanese = 8,
   French,
   Filipino
}

The code above will result to English = 1, Spanish = 2, Chinese = 3, Japanese = 8, French = 9, Filipino = 10

It is a good practice to define a value for 0 in enums to signify "no value" as 0 in enums mean the absence of all properties possible. Defining a value for 0 with make it a valid state for your enum.

enum Languages: byte
{
   None = 0
   English = 1,
   Spanish = 2,
   Chinese = 4,
   Japanese = 8,
   French = 16,
   Filipino = 32
}

This is specifically useful when you are using flags attribute on your enum as this will catch values presented as 0

[Flags]
enum Languages: byte
{
   None = 0, 
   English = 1,
   Spanish = 2,
   Chinese = 4,
   Japanese = 8,
   French = 16,
   Filipino = 32
}

Language ls; //will default to 0
Console.WriteLine(ls); //will print None on the console

Adding the [Flags] attribute to your enums will help you "combine values" of enums into one.

Language ls = Language.English | Language.Filipino | Language.French;
Console.WriteLine("I can speak {0}", ls);

//The code above will print: I can speak English, Filipino, French

Saturday, January 09, 2010 2:40:44 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

All content © 2010, Keith Rull
On this page
This site
Calendar
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: