Wednesday, 22 March 2017

Enumeration in C#

ENUMERATIONS
An enumeration is a special kind of value type limited to a restricted and unchangeable set of numerical values. By default, these numerical values are integers, but they can also be longs, bytes, etc. (any numerical value except char) as will be illustrated below.
When you define an enumeration you provide literals which are then used as constants for their corresponding values. The following code shows an example of such a definition:
1.
public enum DAYS
2.
{
3.
Monday,
4.
Tuesday,
5.
Wednesday,
6.
Thursday,
7.
Friday,
8.
Saturday,
9.
Sunday
10.
}



Note, however, that there are no numerical values specified in the above. Instead, the numerical values are (we think) set up according to the following two rules:
1. For the first literal: if it is unassigned, set its value to 0.
2. For any other literal: if it is unassigned, then set its value to one greater than the value of the preceding literal.
From these two rules, it can be seen that DAYS.Monday will be set to 0, and the values increased until DAYS.Sunday is set to 6. Note also how we are referring to these values - the values specified in an enumeration are static, so we have to refer to them in code using the name of the enumeration: "DAYS.Monday" rather than just "Monday". Furthermore, these values are final - you can't change their runtime value.
The following code demonstrates how you can override the default setting which makes the default values integers. In this example, the enumeration values are set to bytes.
1.
enum byteEnum : byte
2.
{
3.
A,
4.
B
5.
}



You can also override the default numerical values of any and all of the enumeration elements. In the following example, the first literal is set to value 1. The other literals are then set up according to the second rule given above, so DAYS.Sunday will end up equal to 7.
1.
public enum DAYS
2.
{
3.
Monday=1,
4.
Tuesday,
5.
Wednesday,
6.
Thursday,
7.
Friday,
8.
Saturday,
9.
Sunday
10.
}



In the two examples given, the values of each literal has been unique within the enumeration. This is usually how you will want things to be, but in fact the values need not be unique. In the following case, the value of DAYS.Thursday is also set to equal 1. The values assigned to the other literals will follow the rules given previously, so both DAYS.Tuesday and DAYS.Friday will equal 2, etc.
1.
public enum DAYS
2.
{
3.
Monday=1,
4.
Tuesday,
5.
Wednesday,
6.
Thursday=1,
7.
Friday,
8.
Saturday,
9.
Sunday
10.
}



No comments:

Post a Comment