|
|
Title |
Introduction to Enum
|
Summary |
Simple introduction to the use of enum. Enum is a simple way to make code more readable and with intellisence, simpler to write. |
Contributor |
John McTainsh
|
Published |
1-Jan-2004 |
Last updated |
1-Jan-2004 |
|
|
Introduction
Here I will go over some simple features of Enums and ways to use them.
The enum keyword is used to declare an enumeration, a distinct type
consisting of a set of named constants called the enumerator list. Every
enumeration type has an underlying type, which can be any integral type except
char.
Define
Define an Enum as follows. Note in the following segment, the first value Drawing has an
integer value of 0 by default. The remaining values increment until a value is assigned.
enum Mode
{
Drawing, // Default as 0
Selecting, // Default as 1
Dragging, // Default as 2
Rotating = 55 // Assigned to 55
}
Use
The enum can now be used as a readable value rather than a number. Below are some examples
of its use.
Mode m = Mode.Dragging;
...
switch( m )
{
case Mode.Dragging:
...
break;
case Mode.Drawing:
case Mode.Rotating:
...
break;
case Mode.Selecting:
...
break;
}
...
if( m == Mode.Dragging )
{
...
}
// Convert the value to an integer. In this case x = 2.
int x = (int)Mode.Dragging;
Working with the enum value
The enum value can also be converted to and from a string value. This is
very useful in debug with the Visual Studio IDE when you hover over a variable to
see its value. The enum string will appear.
try
{
// Set string to text of dragging, then convert back to Mode value
string sMode = Mode.Dragging.ToString();
Mode mNew = (Mode)Enum.Parse( typeof( Mode ), sMode, false );
Console.WriteLine( "Recovered mode : {0}", mNew.ToString() );
// Load from string (not case sensitive)
Mode mOther = (Mode)Enum.Parse( typeof( Mode ), "selecting", true );
Console.WriteLine( "String to mode : {0}", mOther.ToString() );
// Load from integer
Mode mInt = (Mode)55;
Console.WriteLine( "Integer mode : {0}", mInt.ToString() );
// Try to Parse undefined Mode (THIS WILL THROW EXCEPTION)
Mode mBad = (Mode)Enum.Parse( typeof( Mode ), "BadText" );
Console.WriteLine( "ERROR mode : {0}", mOther.ToString() );
}
catch( ArgumentException ex )
{
Console.WriteLine( "Argument Exception : {0}", ex.Message );
}
The above code will return the following results.
Recovered mode : Dragging
String to mode : Selecting
Integer mode : Rotating
Argument Exception : Requested value BadText was not found.
|