Chapter 6 — Enumerations

SAMS CSHARP 4.0 (Page 116)

Enumeration bridge the gap between numbers and objects.

Declare an Enumeration

Enumerations can be defined within an namespace or classes:

enum BookBinding {

You can use the enumeration like:
BookBinding binding = Bookbinding.Hardcover;

Declare an Enumeration with Explicit Values

enum BookLanguage {
English = 0,
Chinese = 1,
Japanese = 2

Declaring Enumeration as Flags

Determine if a Flag is set

To check if the book is of Vampires genra – use HasFlag.
BookGenras genres = BookGenras.Vampire | BookGenres.Fantasy
bool isVampire = genres.HasFlag(Bookgenres.Vampires)

Convert an Enumeration to an Integer

You need to convert an enumeration to its numeric equivalent.

You need to explicitly convert the value:

int Value = (int)


BookLanguage lang=(BookLanguage) Value.

(make sure you validate the converted enumeration is valid – see next)

Determine if an Enumeration is Valid

bool isDefined = Enum.IsDefined(typeof(bookbinding), badBinding)

List All Enumeration Values

foreach (BookGenres genre in Enum.GetValues(typeof(BookGenres))) {
Console.WriteLine(“\t” + Enum.GetName(typeof(BookGenres), genre));

Convert a String to an Enumeration

use TryParse is easier

string hardcoverstring = “hardcover”;
BookBinding goodbinding;
bool canParse = Enum.TryParse(hardcoverstring, out goodBinding) // this is good/true.
canParse = Enum.TryParse(“gargabe”, out goodBinding) // this is false.

Convert a string to a Set of Flags

Enum.TryParse alo works for flags – multiple flags.

string flagstring=”Vampire, Mystery, ScienceFiction, Vampire”;
BookGenres flagEnum = BookGenres.None;

If (Enum.TryParse(flagString, out flagEnum)) {
// print the genres

Enumeration Tips

* If each enumeration must match external values (such as from DB), then explicitly assign a value to each enumeration member.
* Always use [Flags] Enumeration when you need to combine mulripl values into a single fields (such as when using checkboxes)
* Flag enumerations must have values explicitly assigned that are unique powers of 2 (1, 2, 4, 8, 16….) to work correctly.
* An enumeration should have a singular name if it is not used as flags. If it’s flags, then the enum name should be plural.
* Define a None
vlaue in each Enumeration, with value of 0. This is very important when using [Flags].

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: