Tuesday, July 28, 2009

Enumerations in C#

Enumerations are the mechanism to group related constants. System.Enum class provides the base class for enumerations, it is a value type.
The following example demonstrates using WindowState enum in WPF. In the case of WindowState enumerator there are three constants viz., Maximized, Minimized and Normal.









Creating Enumerations
In the following example I am creating an enum called Tech with three constants Wpf, Silverlight and Xbap and later on I am using using it. Extensive use of enums makes your code more consistent.

enum TEch
{
Wpf, Silverligh, Xbap
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(TEch.Silverligh.ToString());
}

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

In the following example I am extracting the value of the element Wpf.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
int i = (int)TEch.Wpf;
MessageBox.Show(i.ToString());
}


When you run the application you will get 0. If you substitute Wpf with Silverlight or Xbap you will get 1 or 2 respectively.


It is possible to alter the default underlying value by assigning another values.

enum TEch
{
Wpf = 2, Silverligh = 4, Xbap = 6
}









Enum.GetValues() method
Enum.GetValues() method to extract the constants in an Enumeration.
using System.Drawing;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
KnownColor [] color = (KnownColor[])Enum.GetValues(typeof(KnownColor));
foreach (KnownColor colorName in color)
{
listBox1.Items.Add(colorName);
}
}



For this example to work in WPF you should set reference to System.Drawing

No comments:

Post a Comment