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. string abc = GetData(1);
  4. Console.ReadLine();
  5. }
  6. public static string GetData(int i)
  7. {
  8. Dictionary<int, string> ColorData = new Dictionary<int, string>();
  9. ColorData.Add(1, "green");
  10. ColorData.Add(1, "red");
  11. ColorData.Add(1, "blue");
  12. ColorData.Add(1, "yellow");
  13. ColorData.Add(1, "magento");
  14. return ColorData[i].ToString();
  15. }
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. string fruit = "lemon";
  4. string xyz = GetData1(fruit);
  5. }
  6. rivate static string GetData1(string fruit)
  7. {
  8. Dictionary<string, string> ColorFruit = new Dictionary<string, string>();
  9. ColorFruit.Add("lemon", "yellow");
  10. ColorFruit.Add("Orange", "red");
  11. ColorFruit.Add("Mango", "yellow");
  12. ColorFruit.Add("Grapes", "green");
  13. return fruit + " color is " +ColorFruit[fruit].ToString();
  14. }
Please update if you have any doubts or questions.

9 Comments

Join the conversation! Your thoughts help the community grow.

  • Aniket Narvankar

    Nice Article. But any idea on how to add this conditions to dictionary as a key, i have two conditions like a > 0 and a < 0

    • Anson Davis

      Thanks for your feedback.

  • Gajanan Chavhan

    good article. But we can solve same issue with Enum also.

    • Anson Davis

      Thanks for your feedback.

  • Although there are some typing mistakes. Still this article is good.

    • Anson Davis

      Amit Raghuwanshi Thanks for your feedback.

  • this article is very useful thanks 👌👌

    • Anson Davis

      abdo mohamed Thanks a lot for your feedback.