Enumerations are a great construct.They allow you to create a type limited to a set of constant values. Because of this, they are type-safe. Best suited to use them are numerical values like int, long and byte.
The .Net framework makes extensive use of enums-Days of the Week, for example. Using enums eliminates common errors like passing invalid arguments to a function.
For example, you may have a function that accepts the numerical equivalent of a day of the week. It may only accept an integer from 1 to 7. But nothing prevents the code from calling it with a value of 8,9 or 10, etc. Using enumerations, you can define a custom type DayofWeek:
enum DayofWeek
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
So, instead of:
public void foo(int DayOfWeek)
{
}
we have:
public void foo(DayofWeek day)
{
}
By default, each constant in the enumerations will be given an integer value starting from 0. So Monday will have a value of 0, and so on.
Now you won't have to worry about your function being called with invalid arguments.
Till then, see ya!
Peace!
No comments:
Post a Comment