One of the things I find myself using more and more in .Net is the good old Enum. Very often there are a list of choices for a UI or options for things like object states or statuses that we need to represent in code. The most readable way to do that is using an Enum.
Which is better?
Constants:
static void Login()
{
switch (status)
{
case "New":
Console.Write("Welcoome to our site.");
break;
case "Active":
Console.WriteLine("Welcome back.");
break;
case "Inactive":
Console.WriteLine("Your account is inactive. Please contact tech support.");
break;
default:
Console.WriteLine("Invalid user and/or password.");
break;
}
Or Enums:
static void Login()
{
switch (status)
{
case UserStatus.New:
Console.Write("Welcoome to our site.");
break;
case UserStatus.Active:
Console.WriteLine("Welcome back.");
break;
case UserStatus.Inactive:
Console.WriteLine("Your account is inactive. Please contact tech support.");
break;
default:
Console.WriteLine("Invalid user and/or password.");
break;
}
}
Advantages of Enums:
- When compared to using string constants there is a peformance advantage. Enums are value types, created on the stack and not the heap. Translation – it uses fewer resources than strings which are stored on the heap. Is the advantage significant? No probably not, but it does exist.
- Intellisense. Using Enums provides full intellisense support in Visual Studio for your types, categories, colors, statuses, etc. Don’t underestimate the value of this.
-Compile time versus runtime checking of values. At compile you’ll know if the values are valid. No typos, or at least the risk is greatly reduced, with Enums.
-Readability. Great read here about not using "magic numbers" – use Enums instead!!
[Place holder for snarky conclusion sentence.] Enjoy!