I am impressed that the idea of having executable code as the Value of a KeyValuePair in a .NET Dictionary occurred to you. That's something I published an article about on DevX more than eight years ago: [
^] ... do remember that article was written when some features we enjoy in C# .NET now were not available; I would not write the same article today :)
I think Sergey's article is a valuable resource for advanced study of this topic.
One thing to keep in mind, however: a switch/case statement is very efficient, particularly in the case where you use an integer value to determine which Case is executed, and that integer increases in regular order. In that case, the compiler can create a simple jump-table. Dictionaries in .NET are also speedy; under-the-hood they use hash-sets.
You can use the auto-initialize facility of the .NET dictionary, and Lambda expressions (newer addition to C# .NET) to simplify instantiation:
Dictionary<int, Action<int>> BankTransactions = new Dictionary<int, Action<int>>
{
{1, value => Deposit(value)},
{2, value => WithDraw(value)},
{3, value => Enquiry(value)},
{4, value => Exit(0)}
};
private void Deposit(int accountNumber)
{
MessageBox.Show(string.Format("Deposit: {0}", accountNumber));
}
BankTransactions[1](1000);
However, consider the limitation you have created by using a Dictionary like this: you are "locked in" to the requirement that the executable code 'Value for each 'Key in the Dictionary is a method with one integer parameter that returns no result.
In contrast, the code you execute in a Switch/Case statement for each Case can be any code; you can call any method requiring any number of parameters and, if needed, use its return value.
To make the executable method/delegate associated with a Dictionary 'Key accept a variable number of parameters, or parameters of different types, would require late-binding through use of Dynamic, or some other technique, and would cancel any benefit you got from the Dictionary's high-performance look-up capability.
And, now ... okay, I didn't quite tell the "whole story;" look at this:
private string someString = "a string";
private double someDouble = 199.994;
private void Deposit2(int accountNumber, string str, double dbl)
{
MessageBox.Show(string.Format("Deposit: {0} string: {1} double: {2}", accountNumber, str, dbl));
}
BankTransactions.Add(5, value => Deposit2(value, someString, someDouble));
BankTransactions[5](actn);
I have just invoked a method that requires three parameters from a Dictionary Key/Value Pair where the Value Type is an Action with one parameter !
The fact I can do this does not "fill me with joy;" in fact, I recommend you never do this because it will make your code more difficult to read/maintain in the future. imho this "hidden feature" is not consistent with C#'s identify as a strongly-typed language.
I "love" using Dictionaries, but they are
just another tool in your toolbox; use them wisely :)