Replacing Switch Or If Statements With Dictionary

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,
  1. a = "1"  
  2. if (a == 1) {  
  3.     console.write("Number is " + a + "Color is green");  
  4. else if (a == 2) {  
  5.     console.write("Number is " + a + "Color is red");  
  6. else if (a == 3) {  
  7.     console.write("Number is " + a + "Color is blue");  
  8. else if (a == 4) {  
  9.     console.write("Number is " + a + "Color is yellow");  
  10. else {  
  11.     console.write("Number is " + a + "Color is magento");  
  12. }  
In programming if we have so many statments like this we can replace them with Dictionary:
  1. static void Main(string[] args)    
  2.         {    
  3.     
  4.             string abc = GetData(1);    
  5.             Console.ReadLine();    
  6.         }    
  7.     
  8. public static string GetData(int i)    
  9.         {    
  10.             Dictionary<intstring> ColorData = new Dictionary<intstring>();    
  11.             ColorData.Add(1, "green");    
  12.             ColorData.Add(1, "red");    
  13.             ColorData.Add(1, "blue");    
  14.             ColorData.Add(1, "yellow");    
  15.             ColorData.Add(1, "magento");    
  16.             return ColorData[i].ToString();    
  17.     
  18.         }    
Switch case normal coding:
  1. static void Main()  
  2.     {  
  3.         string fruit = "Lemon";  
  4.         switch (fruit )  
  5.         {  
  6.             case "lemon":  
  7.                 Console.WriteLine("lemon color is yellow");  
  8.                 break;  
  9.             case "orange":  
  10.                 Console.WriteLine("orange color is orange");  
  11.                 break;  
  12.             case "mango":  
  13.                 Console.WriteLine("mango color is yellow");  
  14.             case "Grapes":  
  15.                 Console.WriteLine("gapes color is green");  
  16.         }  
  17.     }  
Switch case example with dictionary.
  1. static void Main(string[] args)  
  2.        {  
  3.   
  4.            string fruit = "lemon";  
  5.            string xyz = GetData1(fruit);  
  6.        }  
  7.   
  8. rivate static string GetData1(string fruit)  
  9.        {  
  10.            Dictionary<stringstring> ColorFruit = new Dictionary<stringstring>();  
  11.            ColorFruit.Add("lemon""yellow");  
  12.            ColorFruit.Add("Orange""red");  
  13.            ColorFruit.Add("Mango""yellow");  
  14.            ColorFruit.Add("Grapes""green");  
  15.            return  fruit + " color is " +ColorFruit[fruit].ToString();  
  16.        }  
Please update if you have any doubts or questions.