This post contains information about enumerations, the
enum
keyword, and how it is used in the C# language.Enumerations in C#:
By using the
enum
keyword, we can attach named values to integers. This is usually done for two reasons:
- to make code more 'human-readable' -- we can replace things like
item = 1;
withitem = apple;
- to stop any possible errors available from 'falling off the end of a list' of values which are internal to the code
Quick Rules:
- Enumerations should be organized as follows: the
enum
keyword, the identifier, an opening brace, a comma separated list of values, a closing brace, a trailing semi-colon - If no explicit values are given to the
enum
then the compiler will assign ascending integer values starting from zero - Basic enumerations provide named values to attach to integers e.g.:
- Basic (integer) enumerations can be explicitly forced to take values other than the compiler defaults e.g.:
- Basic (integer) enumerations are treated as integers by the compiler and may be added and subtracted as such e.g.:
- Explicit casts can be made to and from integer types e.g.:
- Enumerated values can be combined with a bitwise-OR operator e.g.:
- Any integer type other than
int
can be used to specify anenum
if required e.g.:
Example 1: Basic
enum
usage:
Example 2: Hand enumeration and overlap of values:
Example 3: Explicit casts are required to access the integer value of the
enum
:
Example 4: Use of the
ToString
method to access the name of an enumeration:
References:
[1] Wikipedia -- C# Syntax[2] Wikibooks -- C# enumerations
No comments:
Post a Comment