Correct way to index a small collection of values

c#

Solution

A `switch` statement will end up being translated into a `Dictionary` eventually. It often makes sense on more complex examples (such as this one) to go straight to that.

Dictionary<string, string> currencyLookup = new Dictionary<string, string>();
currencyLookup["USD"] = "$";
//...

string currency = currencyLookup["INR"];

Some of the advantages of using a dictionary:

- It can require a tad less code if you want to define all of the options as literals. (Particularly if using collection initializers.)

- You can populate the dictionary based on information in a file, from a database, or some other external source so that you don't need to define all of the mappings in code. In addition to making the code cleaner, this let you add/remove/change currencies without needing to re-compile your program.

- You have access to operations such as `ContainsKey` to know whether or not a particular key exists, as opposed to just returning an empty string if it's not found (which you can still do as well).

Problem

What is the best way to do something like the following where an id is passed to a method. Is a case statement ok or some sort of collection like a hashtable better? ``` private string GetCurrencySymbol(string code) { switch (code) { case "USD": case "AUD": case "CAD": case "NAD": case "NZD": case "SGD": case "HKD": return "$"; case "GBP": return "£"; case "NOK": case "DKK": case "SEK": return "kr"; case "ZAR": return "R"; case "JPY": return "¥"; case "CHF": return "CHF"; case "EUR": return "€"; case "GHS": return "¢"; case "BWP": return "P"; case "INR": return "₹"; case "KES": return "KSh"; case "LSL": return "L"; case "MUR": return "Rs"; case "NGN": return "₦"; case "MWK": return "MK"; case "MZM": return "MT"; case "PKR": return "Rs"; case "PLN": return "zł"; case "SZL": return "L"; case "TZS": return "Sh"; case "UGX": return "Sh"; case "ZMK": return "ZK"; default: return ""; } } ``` This seems to smell a bit? It's not accessed all that often but seems a bit verbose.

Original source