|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article will review some basic concepts of the C# language and present examples of advanced programming with enums. The aim is to review enums in detail and to use this concept of the language to produce better quality code in everyday programming. EnumsThe
The default underlying type is enum Color {White, Red, Blue, Green, Black};
The You can override the first enumerator value, for example: enum Color {White=2, Red, Blue, Green, Black};
Now, the enumerator values are You also can set every enumerator's value. To extract the default values from an enum, you can use the enum Color {White=2, Red, Blue, Green, Black};
Color myColor = default(Color);
Console.WriteLine("Color = {0}", myColor);
Here is the output: Color = 2
Enum data typeEach enum has an underlying type; the default type is // Use byte enumerators
enum Color :byte { White, Red, Blue, Green, Black };
// Use long enumerators
enum Limite :long {Down = 0L, Up = 2147483648L};
You can assign any value in the range of the underlying enum to a variable of type Enum bit flags and FlagsAttributeUsing enumerators as bit flags can be useful to combine options or settings without creating separate properties. To enable bitwise combination of enumerators, you must start by setting up each enumerator with a bit mask flag. Look at the binary comments to understand why we are using 1, 2, 4. public enum DocumentPermissions {
Modify = 1, // 001
Read = 2, // 010
Write = 4, // 100
FullControl = Modify | Read | Write // 111
};
So, if we want to check if an enum variable " public class PermissionValidator {
public static bool CheckModify (DocumentPermissions doc) {
return ((int)doc & (int)DocumentPermissions.Modify) == 1;
}
}
// Modify
DocumentPermissions permission = DocumentPermissions.Modify;
Console.WriteLine ("Result 1 = {0}", PermissionValidator.CheckModify (permission));
// FullCOntrol
permission = DocumentPermissions.FullControl;
Console.WriteLine ("Result 2 = {0}", PermissionValidator.CheckModify (permission));
// Read permission = DocumentPermissions.Read;
Console.WriteLine ("Result 3 = {0}", PermissionValidator.CheckModify (permission));
Here is the output: Result 1 = True
Result 2 = True
Result 3 = False
Now, we will see a logical operation using '&', the logical operation 'AND'. The operation below uses the same values as the code:
Below is an illustration of the [Flags]
public enum DocumentPermissionsFlag {
Modify = 1, // 001
Read = 2, // 010
Write = 4, // 100
FullControl = Modify | Read | Write // 111
};
Without the DocumentPermissions permission =
DocumentPermissions.Modify | DocumentPermissions.Write;
Console.WriteLine("Output 1 = {0}", permission.ToString());
Here is the output: Output 1 = 5
Now, with the Flags attribute, DocumentPermissionsFlag permissionFlag =
DocumentPermissionsFlag.Modify | DocumentPermissionsFlag.Write;
Console.WriteLine ("Output 2 = {0}", permissionFlag.ToString());
Here is the output: Output 2 = Modify, Write
Cast int and string to enumThe casting of a Below is an example of a DocumentPermissions permission =
(DocumentPermissions)Enum.Parse (typeof (DocumentPermissions), "Write");
Console.WriteLine ("Output {0}", permission.ToString ());
Now, an example of an permission =
(DocumentPermissions)Enum.ToObject (typeof (DocumentPermissions), 4);
Console.WriteLine ("Output {0}", permission.ToString ());
// Equivalent to
permission = (DocumentPermissions) 4;
The two previous calls may cause an error if the In the example below, I use Now, we will discuss about a generic cast. To create a method that casts a string or an integer to any type of enum, we can use the Since version 2 of the .NET Framework, it is possible to have one method that returns the deferent’s data type. Below is an example with the type public static T CastToEnum<T> (string name) {
if (Enum.IsDefined (typeof (T), name)) {
return (T)Enum.Parse (typeof (T), name);
}
else { //No enum for string name
throw new
ArgumentOutOfRangeException (
string.Format ("{0}...{1}", name, typeof (T).ToString()));
}
}
//Animal enum
public enum Animal {
Dog = 1,
Cat,
Mouse,
Bird,
Tiger
};
// Use EnumHelper
Animal animal = EnumHelper.CastToEnum<Animal> ("Dog");
Console.WriteLine ("Output {0}", animal.ToString ());
Here is the output: Output Dog
In the source code of the article, you will find a class Enum enumeratorsWe have the possibility to enumerate an enumerator’s names and values using the foreach (string name in Enum.GetNames (typeof (Animal))) {
System.Console.WriteLine (name);
}
Here is the output: Dog
Cat
Mouse
Bird
Tiger
Now, an example enumerating the enum values using foreach (int name in Enum.GetValues (typeof (Animal))) {
System.Console.WriteLine (name);
}
Here is the output: 1
2
3
4
5
The same method can count the items on an enum. The System.Console.WriteLine ("Count = {0}",
Enum.GetValues (typeof (Animal)).Length);
Here is the output: Count = 5
VS 2005-2008 code completionYou can easily create a « switch » from an enum variable with Visual Studio 2005-2008.
Animal animal;
Note: Visual Studio create the enum skeleton and selects the " switch (switch_on) {
default:
}
Note: The editor automatically creates the cases for the switch (animal) {
case Animal.Dog:
break;
case Animal.Cat:
break;
case Animal.Mouse:
break;
case Animal.Bird:
break;
case Animal.Tiger:
break;
default:
break;
}
Be attentive to the default path; in many cases, the switch enum does not require a default path. Good coding practices using enumsUsing enums instead of hard coded values can improve your coding quality, but be careful of design mistakes. Good practices
Bad practices
ConclusionI hope that this article will help you to improve your code; if you have any questions or remarks, please add a comment. I will respond as soon as possible. History
|
||||||||||||||||||||||