Tuesday, August 18, 2009

Using enum in C# for smart coding




Most of us have written these (Sample 1 & Sample 2) kind of code snippet in our student or even professional life:

Sample 1 (C# Code):
string employeeType = employeeTypeComboBox.Text;
if (employeeType == "Permanent")
{
CalculateSalary();
}
else if (employeeType == "Worker")
{
CalculateWages();
}
else
{
// Do nothing
}

Sample 2 (C# Code):
string studentType = studentTypeComboBox.Text;
if (studentType == "Regular")
{
// Do Something
}
else if (studentType == "Private")
{
// Do Something
}
else
{
// Do nothing
}
In these two samples, user input is taken in a string valriable (employeeType /studentType) from a ComboBox and compare the variable with some discrete hard-coded string values (Permanent/Worker/Regular/Private).
What will happen if you type (some of you has faced these sad experiences) Parmanent instead of Permanent in Sample 1? Definitely, CalculateSalary() method will be not called and even program doesn’t show you any error message (any compile error). In best case, You will find out this problem during development and fix it immediately. But in worst case this problem arises after demployment.


Is there any solution where my typo will be detected earliar and show me a compile error?
Yes. Try emun.


See Sample Code 3, the more smart version of Sample code 1. Here you have no typo option.


Sample Code 3
enum EmployeeType
{
Permanent,
Worker
}
string employeeType = employeeTypeComboBox.Text;
if (employeeType == EmployeeType.Permanent.ToString())
{
CalculateSalary();
}
else if (employeeType == EmployeeType.Worker.ToString())
{
CalculateWages();
}
else
{
//Do Nothing
}

Believe me still you have chance to improve the code quality of Sample Code 3. Just see the Sample Code 4, I have wipe out all kinds of string variable from Sample Code 3.


Sample Code 4:
EmployeeType selectedEmployeeType = (EmployeeType)Enum.Parse(typeof(EmployeeType), employeeTypeComboBox.Text);
if (selectedEmployeeType == EmployeeType.Permanent)
{
CalculateSalary();
}
else if (selectedEmployeeType == EmployeeType.Worker)
{
CalculateWages();
}
else
{
//Do Nothing
}

Even, as your input comes from employeeTypeComboBox, don’t write hard-coded string in it’s item list, rather do it:
employeeTypeComboBox.DataSource = Enum.GetNames(typeof(EmployeeType));

So, why enum?
a) To improve code clarity
b) Make the code easier to maintain
c) Getting error at earlier stage

Note:
a) You can define enum inside or outside of class, but not inside of method or property.
b) The list of names contained by a particutar type of enum called enumerator list.


More About enum:
a) If you want you can keep value with each name in enumerator list. Example:


enum Priority
{
   Critical = 1,
   Important = 2,
  Medium = 3,
   Low = 4
};


You will get this value by type casting to the related type.
int priorityValue = (int) Priority.Medium;


b) Another nice thing, you can easily iterate through enumerator list.
foreach(Priority priority in Enum.GetValues(typeof(Priority)))
{
   MessageBox.Show(priority.ToString());
}
or even
for (Priority prio = Priority.Low; prio >= Priority.Critical; prio--)
{
   MessageBox.Show(prio.ToString());
}


Conclusion:
You should avoid string operation (specially comparison) because it decreases readability and introduces opacity. But using enum you can increase code readability, discover bugs in design time and keep your code more easy to maintain. So, Instead of string operation we should use enum (where applicable)  as described in this discussion.

5 comments:

  1. thanks brother. This will be helpful to anyone interested in programming.
    We are expecting a lot more from you. keep going.

    A Rahim Khan

    ReplyDelete
  2. Thank you Rahim. I will try to write more. Yesterday i wrote on another topic, "Sufferings with switch smell". You can find it here:
    http://ztiemoon.blogspot.com/2009/09/sufferings-with-switch-smell.html

    ReplyDelete
  3. That discussion is really helpful to understand enumeration class clearly ...thanks brother.please keep continue for us.

    ReplyDelete
  4. nice one. Neat and clear explanation of enum Type. keep going...

    ReplyDelete
  5. Last day I was talking about this and I got the link from you . Thank you Brother for sharing this. It will helps a lot to understand enum.

    ReplyDelete