c# - Is there any good alternative struct for using inside switch case? -
i have switch case showing text in program. wonder can use dictionary or enum numbers , texts? or using switch case this?
string result; int number = int.parse(console.readline()); switch (number) { case 1: result += "ten"; break; case 2: result += "twenty"; break; case 3: result += "thirty"; break; case 4: result += "fourty"; break; case 5: result += "fifty"; break; case 6: result += "sixty"; break; case 7: result += "seventy"; break; case 8: result += "eighty"; break; case 9: result += "ninety"; break; default: result += ""; break; }
it's little less verbose use dictionary{int,string}
in scenario:
var dictionary = new dictionary<int, string>(9) { {1, "ten"}, {2, "twenty"}, {3, "thirty"}, {4, "fourty"}, {5, "fifty"}, {6, "sixty"}, {7, "seventy"}, {8, "eighty"}, {9, "ninety"}, };
string dictionaryentry; if (dictionary.trygetvalue(number, out dictionaryentry)) { result += dictionaryentry; }
also, if plan lot of string concatenations, consider using stringbuilder instead of string result
.
for routines perform extensive string manipulation (such apps modify string numerous times in loop), modifying string repeatedly can exact significant performance penalty. alternative use stringbuilder, mutable string class.
Comments
Post a Comment