If we have so many if else satements or switch statements it is not good coding. We can use a dictionary for solving this problem.
The following if statment is an example,
- a = "1"
- if (a == 1) {
- console.write("Number is " + a + "Color is green");
- } else if (a == 2) {
- console.write("Number is " + a + "Color is red");
- } else if (a == 3) {
- console.write("Number is " + a + "Color is blue");
- } else if (a == 4) {
- console.write("Number is " + a + "Color is yellow");
- } else {
- console.write("Number is " + a + "Color is magento");
- }
In programming if we have so many statments like this we can replace them with Dictionary:
- static void Main(string[] args)
- {
-
- string abc = GetData(1);
- Console.ReadLine();
- }
-
- public static string GetData(int i)
- {
- Dictionary<int, string> ColorData = new Dictionary<int, string>();
- ColorData.Add(1, "green");
- ColorData.Add(1, "red");
- ColorData.Add(1, "blue");
- ColorData.Add(1, "yellow");
- ColorData.Add(1, "magento");
- return ColorData[i].ToString();
-
- }
Switch case normal coding:
- static void Main()
- {
- string fruit = "Lemon";
- switch (fruit )
- {
- case "lemon":
- Console.WriteLine("lemon color is yellow");
- break;
- case "orange":
- Console.WriteLine("orange color is orange");
- break;
- case "mango":
- Console.WriteLine("mango color is yellow");
- case "Grapes":
- Console.WriteLine("gapes color is green");
- }
- }
Switch case example with dictionary.
- static void Main(string[] args)
- {
-
- string fruit = "lemon";
- string xyz = GetData1(fruit);
- }
-
- rivate static string GetData1(string fruit)
- {
- Dictionary<string, string> ColorFruit = new Dictionary<string, string>();
- ColorFruit.Add("lemon", "yellow");
- ColorFruit.Add("Orange", "red");
- ColorFruit.Add("Mango", "yellow");
- ColorFruit.Add("Grapes", "green");
- return fruit + " color is " +ColorFruit[fruit].ToString();
- }
Please update if you have any doubts or questions.