I would first encourage you to read this small post by Microsoft.
In C#, enums cannot have a behaviour. If it helps, you can think of enums as members of a special class where instances just have names but no methods [this is strictly speaking not a correct visualization].
Class members however can have useful methods embedded into them.
Example,
public struct Color {
public static readonly Blue = new Color (0, 0, 255);
public static readonly Red = new Color (255, 0, 0);
//...etc.
public int GetHue() {
//Return the hue of the color
}
public int GetSimilarityCoefficient(Color another_) {
//Some really ingenious algo to identify similarity of colors
}
}
vs.
public enum Color {
Blue,
Red,
Green
} //Cannot do anything much but use if-else/switch-case and make decisions in those blocks
This shows enums in a bad light and hence comes the question —when to use enums? And thus comes a highly personal, though I hope not widely rejected, answer.
I personally prefer to use enums when my members are supposed to only have token meanings (i.e., they are pure states) and when I want them to be extremely lightweight and when I want to ensure that all enumerations can be accounted for.
Example in a form that has several radio button choices (let's say to choose which type of copy to run),
public enum UserChoice {
Copy,
DeepCopy,
PreviewOnly
}
…
//Somewhere
UserChoice userChoice = form.GetUserChoice();
switch (userChoice) {
case UserChoice.Copy:
//Run the copy algorithm
break;
case UserChoice.DeepCopy:
//Run the deep copy algorithm
break;
//Forgot to handle PreviewOnly —> gives a compile exception
}
Note that I can accomplish the same using class variables too:
public class UserChoice {
public static UserChoice Copy = new UserChoice();
public static UserChoice DeepCopy = new UserChoice();
public static UserChoice PreviewOnly = new UserChoice();
}
…
//Then somewhere
UserChoice userChoice = form.GetUserChoice();
if (userChoice == UserChoice.Copy) {
//Run the copy algorithm
}
else if (userChoice == UserChoice.DeepCopy) {
//Run the deep copy algorithm
}
//Forgot to handle preview only. No compile exception.
Also, enums can be Flags.
[Flags]
public enum UserChoice{
Copy = 0,
Deep = 1,
Preview = 2,
NoActualOp = 4
} //Thus, DeepCopy = Copy | Deep; DeepCopyWithPreview = Copy | Deep | Preview; CopyWithPreviewOnly = Copy | Preview | NoActualOp etc..