Friday, June 5, 2009

Enums - Simplify Your Method Options

Intro
Often people will tell you to make your methods do one thing and one thing only, but what if you _are_ doing one thing and you need to tweak the behavior slightly to save yourself from a bunch of duplicate code? Here is a handy way to use an enum to save you and your fellow coders confusion if you decide to change method or class behavior using a parameter.

The Enum: DoSomethingOptions
Do something options is an enumeration which will be used by a switch statement in the method shown below, DoSomethingWithTwoInts. I am not sure what the best practice is, but I tend to declare my enums in the same namespace as the class with which they are intended to be used.
Here is my DoSomethingOptions enum:


enum DoSomethingOpions
{
add
,
subtract,
multiply
}


Hot damn that is simple.

The Method: DoSomethingWithTwoInts(int a, int b)
DoSomethingWithTwoInts is a blatant example of a blatant example, but I hope it will illustrate how enumerations can be handy. The default behavior for DoSomethingWithTwoInts will be addition, but an overloaded method will allow you to specify an alternate behavior implemented with an switch statement controlled by the DoSomethingOptions enum.

public int DoSomethingWithTwoInts(int a, int b)
{
return DoSomethingWithTwoInts(a, b, DoSomethingOpions.add);
}

public int DoSomethingWithTwoInts(int a, int b, DoSomethingOpions Option)
{
switch (Option)
{
case DoSomethingOpions.add:
{
return a + b;
}
case DoSomethingOpions.multiply:
{
return a * b;
}
case DoSomethingOpions.subtract:
{
return a - b;
}
}
}

Enums also work great with the Visual Studio's snippets. If you pull up the switch snippet and enter an enum, VS will automatically build out the switch's case statements using the contents of your enum.

Using enums for this sort of functionality is more readable than arbitrary codes (that you have to enter, since enums are just lists of numbers in the end) and it allows you use intelliSence while filling out your method calls to specify the behavior.

Enums - What to do during the week.

using System;

namespace Keyword_Enum
{
class Program
{
static void Main(string[] args)
{
//pass enum into a function
Console.WriteLine(WhatToDo(DaysInItalian.Sabato));
Console.WriteLine(WhatToDo(DaysInItalian.Domenica));

//enums are zero-index based, go through 5 days
for (int i = 0; i <= 4; i++)
{
//cast int to enum, then pass the enum into a function
Console.WriteLine(WhatToDo((DaysInItalian)i));
}

Console.Read();
}

static string WhatToDo(DaysInItalian giorni)
{
switch (giorni)
{
case DaysInItalian.Sabato:
return "Lovely day for a guiness.";
case DaysInItalian.Domenica:
return "Walk around the park.";
default:
return "Back to work.";
}
}

}

enum DaysInItalian
{
Lunedi, Martedi, Mercoledi, Giovedi, Venerdi, Sabato, Domenica
}

}

Enum

What's up with Enums?

Tuesday, May 19, 2009

C# Keywords

Taking the C# love to an uncomfortable place.