Monday, July 2, 2007

Enum Types in .NET or C# .NET

Enum types implicitly inherit the System.Enum type in the Base Class Library (BCL). This also means that you can use the members of System.Enum to operate on enum types.

I have included few code snippets which are self-explanatory for use of enums.

public
enum Volume : byte
{
Low = 1,
Medium,
High
}


void ShowVolume(int v)

{

Volume vol = (Volume)v;

If(vol == Volume.Low)


}


// get a list of member names from Volume enum,
// figure out the numeric value, and display
foreach (string volume in Enum.GetNames(typeof(Volume)))
{
Console.WriteLine("Volume Member: {0}\n Value: {1}",
volume, (byte)Enum.Parse(typeof(Volume), volume));
}


// get all values (numeric values) from the Volume
// enum type, figure out member name, and display
foreach (byte val in Enum.GetValues(typeof(Volume)))
{
Console.WriteLine("Volume Value: {0}\n Member: {1}",
val, Enum.GetName(typeof(Volume), val));
}


Given the type of the enum, the GetValues method of System.Enum will return an array of the given enum's base.

1 comment:

chirag said...

Simplest way of using Enums is...

Enum.Parse(typeof(yourEnumerator), "anydigit or anyvalueinenum") -> Either convert this to string or mostly to an int.

e.g.
Convert.ToInt16(Enum.Parse(typeof(volume),"High")) should give 1.

 
Dotster Domain Registration Special Offer