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,
In programming if we have so many statments like this we can replace them with Dictionary:
- 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");
- }
- 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();
- }
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Aniket NarvankarPosted Sep 21, 2021, 5:05 AM
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
Viknaraj ManogararajahPosted Jul 21, 2018, 10:49 PM
Nice Article, Thank you for sharing
Gajanan ChavhanPosted Jun 19, 2018, 11:48 PM
good article. But we can solve same issue with Enum also.
Amit RaghuwanshiPosted Jun 5, 2018, 10:45 PM
Although there are some typing mistakes. Still this article is good.
abdo mohamedPosted Jun 5, 2018, 9:08 PM
this article is very useful thanks 👌👌