[go: up one dir, main page]

0% found this document useful (0 votes)
164 views5 pages

Enum C#

The document discusses enums in C#, including how to declare, define values for, use operators on, declare flags for, parse from strings, and best practices for enums.

Uploaded by

Manish Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views5 pages

Enum C#

The document discusses enums in C#, including how to declare, define values for, use operators on, declare flags for, parse from strings, and best practices for enums.

Uploaded by

Manish Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Enum C#

In this article, we will learn:


What is Enumeration?
How to Declare Enumeration in C# ?
How to Declare flag as Enumeration in C# ?
Enum Conversions in C#
Enum Operators in C#

What is Enumeration?

An enum is a distinct value typewith a set of named constants

It is declared by using keyword Enum

Every Enum type has an underlying type which can be any integral type except char.
The default underlying type is int.

The first enumerator has the value 0 by default and the value of each successive
enumerator is increased by 1

Enumeration bridge the gap between numbers and objects

How to declare Enumeration in C# ?

1 enum colors
2 {
3 Red = 1,

4 Blue = 2,
5 Yellow = 3,
6 Green = 4
7 };

This code declares a colors enumeration containing four values.


Lets look at below example to understand how to override the default values.

1 enum Months {Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec };

In Months enumeration, Jan is 0, feb is 1, Mar is 2 and so forth.


Enumerators can have initializers to override the default values.

1 enum Months {Jan=1,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec };

Enum Operators:
The operators that work with enums are:= == != < > <= >= + ^ & | ~ += -= ++ sizeof
The bitwise, arithmetic, and comparison operators return the result of processing the
underlying integral values.
Addition is permitted between an enum and an integral type, but not between two enums.

How to declare flag as Enumeration in C# ?


If you decorate an Enumeration with Flags attribute, the Enumeration represents a
combination of values
Lets look at the below example.

1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3

[Flags]
enum BookGenres
{
None = 0,
ScienceFiction = 0x01,
Crime = 0x02,
Romance = 0x04,
History = 0x08,
Science = 0x10,
Mystery = 0x20,
Fantasy = 0x40,
Vampire = 0x80,
};

You can use the BookGenres enumeration in bit-field operations. To see what [Flags]does,
examine the following code and its output:

1 BookBinding binding = BookBinding.Hardcover;


2 BookBinding doubleBinding =BookBinding.Hardcover | BookBinding.Paperback;
3 Console.WriteLine(Binding: {0}, binding);
4 Console.WriteLine(Double Binding: {0}, doubleBinding);
5 BookGenres genres = BookGenres.Vampire | BookGenres.Fantasy | BookGenres.Romance;
6 Console.WriteLine(Genres: {0}, genres);

Output:
Binding: Hardcover
Double Binding: 3
Genres: Romance, Fantasy, Vampire
Note that the enumeration with the [Flags] attribute printed out each genre correctly.

Determine if a flag is set:


The standard way of doing this is to use the bitwise & operator:

1 BookGenres genres = BookGenres.Vampire | BookGenres.Fantasy;


2 bool isVampire = ((genres &amp; BookGenres.Vampire)!=0);

However, .NET 4 introduces the HasFlag() method, which accomplishes the same thing:

1 bool isVampire = genres.HasFlag(BookGenres.Vampire);

List Enumeration values


To get a list of all defined values for a specific enumeration, you can use Enum.GetValues(),
as shown below:

1 foreach (BookGenres genre in Enum.GetValues(typeof(BookGenres)))


2{
3 Console.WriteLine(\t + Enum.GetName(typeof(BookGenres), genre));
4}

Enum.GetName() returns the same string you would get if you just called ToString()on a
value.
You can also use Enum.GetNames() to get all the strings back directly

Convert a String to an Enumeration


Enum contains a standard Parse() method but this can throw exceptions and requires you
to cast the result to the desired enumeration type.
Instead, you can use TryParse(), which is both safe and strongly typed, using generics, as
in this code

Example:

1 string hardcoverString = hardcover;


2 BookBinding goodBinding, badBinding;
3 //this succeeds
4 bool canParse = Enum.TryParse(hardcoverString, out goodBinding);
5 //this fails
6 canParse = Enum.TryParse(garbage, out badBinding);

Best Practices to use Enumerations:

If your enumerations must match external values, then explicitly assign a value to
each enumeration member.

Always use [Flags] when you need to combine multiple values into a single field.

Flag enumerations must have values explicitly assigned that are unique powers of
two (1, 2, 4, 8, 16, and so on) to work correctly.

An enumeration should have a singular name if it is not used as flags, whereas flags
should have plural names.

Define a None value in each enumeration, with value of 0. This is especially


important when using [Flags].

2016, admin. All rights reserved.

You might also like