I have two scenarios that use the same switch structure. Rather than creating two switches that are basically duplicates, is there a way to reuse the structure?
First scenario:
switch (someString)
{
case constant1:
//create class1
break;
case constant2:
//create class2
break;
default:
break;
}
Second scenario:
switch (someString)
{
case constant1:
return true;
case constant2:
return true;
default:
return false;
}
Well, you could have:
private static readonly Dictionary<string, Func<Foo>> SomeSensibleName =
new Dictionary<string, Func<Foo>>
{
{ Constant1, () => new Class1() },
{ Constant2, () => new Class2() },
...
};
Then in place of the first:
Func<Foo> factory;
if (SomeSensibleName.TryGetValue(someString, out factory))
{
Foo result = factory();
// Use it, presumably...
}
And in place of the second:
return SomeSensibleName.ContainsKey(someString);
Is that the sort of thing you were looking for?
See more on this question at Stackoverflow