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();
- }

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 👌👌