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.
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:
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).The case statement is perfect in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With