You have a few options... it depends on the situation, really.
Assuming a case like:
enum MyEnum { Foo, Bar, Baz }
bool method(MyEnum val)
{
switch (val)
{
case MyEnum.Foo:
Console.WriteLine("Some");
Console.WriteLine("big");
Console.WriteLine("case");
Console.WriteLine("statement");
Console.WriteLine("that");
Console.WriteLine("Foo");
Console.WriteLine("does");
return true;
case MyEnum.Bar:
throw new Exception("Bar!");
case MyEnum.Baz:
Console.Beep();
Console.WriteLine("Beep.");
return false;
default:
throw new ArgumentOutOfRangeException("val");
}
}
One possibility is to take the bodies of the case statements and make methods out of them.
bool method(MyEnum val)
{
switch (val)
{
case MyEnum.Foo:
return FooMethod();
case MyEnum.Bar:
return BarMethod();
case MyEnum.Baz:
return BazMethod();
default:
throw new ArgumentOutOfRangeException("val");
}
}
bool FooMethod()
{
Console.WriteLine("Some");
Console.WriteLine("big");
Console.WriteLine("case");
Console.WriteLine("statement");
Console.WriteLine("that");
Console.WriteLine("Foo");
Console.WriteLine("does");
return true;
}
bool BarMethod()
{
throw new Exception("Bar!");
}
bool BazMethod()
{
Console.Beep();
Console.WriteLine("Beep.");
return false;
}
Another is to create a dictionary of key to delegate, and do a dictionary lookup/invoke in place of a switch.
delegate bool BoolFunc();
readonly Dictionary<MyEnum, BoolFunc> methods;
MyClassConstructor()
{
methods = new Dictionary<MyEnum, BoolFunc>();
methods.Add(MyEnum.Foo, FooMethod);
methods.Add(MyEnum.Bar, BarMethod);
methods.Add(MyEnum.Baz, BazMethod);
}
bool method(MyEnum val)
{
BoolFunc funcToCall;
if (!methods.TryGetValue(val, out funcToCall))
throw new ArgumentOutOfRangeException("val");
return funcToCall.Invoke();
}
bool FooMethod()
{
Console.WriteLine("Some");
Console.WriteLine("big");
Console.WriteLine("case");
Console.WriteLine("statement");
Console.WriteLine("that");
Console.WriteLine("Foo");
Console.WriteLine("does");
return true;
}
bool BarMethod()
{
throw new Exception("Bar!");
}
bool BazMethod()
{
Console.Beep();
Console.WriteLine("Beep.");
return false;
}
Another is to look for an object-oriented way where you differentiate behavior by overriding an abstract/virtual method, in place of a switch statement somewhere.
bool method(MyNonEnumClass val)
{
return val.DoYourThing();
}
abstract class MyNonEnumClass
{
public abstract bool DoYourThing();
}
class FooClass : MyNonEnumClass
{
public override bool DoYourThing()
{
Console.WriteLine("Some");
Console.WriteLine("big");
Console.WriteLine("case");
Console.WriteLine("statement");
Console.WriteLine("that");
Console.WriteLine("Foo");
Console.WriteLine("does");
return true;
}
}
class BarClass : MyNonEnumClass
{
public override bool DoYourThing()
{
throw new Exception("Bar!");
}
}
class BazClass : MyNonEnumClass
{
public override bool DoYourThing()
{
Console.Beep();
Console.WriteLine("Beep.");
return false;
}
}
All depends, though. :)