Friday 27 April 2012

Usage Of Enum


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. 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
Enumerations (enums) make your code much more readable and understandable.  If you are ever writing code that looks like
if (Size == "3") // For e.g 1 - Small,2-Medium,3-Large
It will be so difficult for future developers to understand what this code is supposed to do, and it will require you to add another line saying
// Size 3 is For Large

However, if you did something nicer like,
if(Shape==Size.Small)
CW("This is Small Size")
You have automatically documented your code and made it easier to understand.  One way to reduce the amount of documentation that you have to put in the code is to use tricks such as Enums (C#) to make the code sufficiently clear.
A magic number is a number you use in the code, that is ‘magical’, in the sense that nobody knows where it came from.

List of named constantsDeclaration (directly in a namespace)

enumColor {red, blue, green} // values: 0, 1, 2
enumAccess {personal=1, group=2, all=4}
enumAccess1 : byte{personal=1, group=2, all=4}
Usage in Code :

Color c = Color.blue; // enumeration constants must be qualifiedAccess a = Access.personal | Access.group;if ((Access.personal & a) != 0) 
Console.WriteLine("access granted");



Operations on Enumerations
Compare
if (c == Color.red) ...if (c > Color.red && c <= Color.green) ...+, -c = c + 2;++, --c++;&if ((c & Color.red) == 0) ...|c = c | Color.blue;~c = ~ Color.red;The compiler does not check if the result is a valid enumerationvalue.Note-Enumerations cannot be assigned to int(except after a type cast).-Enumeration types inherit from object(Equals, ToString, ...).-Class System.Enumprovides operations on enumerations(GetName, Format, GetValues, ...).

Compare if (c == Color.red) ...

if (c > Color.red && c <= Color.green) ...
+, - c = c + 2;
++, -- c++;
& if ((c & Color.red) == 0) ...
| c = c | Color.blue;
~ c = ~ Color.red;


No comments:

Post a Comment

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...