I have a program that has the following code:
foreach (string section in DataAccessLayer.AcceptedSections)
{
switch (section)
{
case "Section1":
Console.WriteLine("Section 1");
break;
case "Section2":
Console.WriteLine("Section 2");
break;
case "Section3":
Console.WriteLine("Section 3");
break;
default:
Console.WriteLine("Default section");
break;
}
}
Is there anyway i can do what this code does without providing the section’s string again within the case? The DataAccessLayer.AcceptedSections is dynamic and i don’t want to have to add another section case to my code, rebuild and redeploy every time a new section comes on board. It’s Friday and my mind is not working very well.
For Example:
I don’t want to add the following code when Section 4 gets added to the database:
case "Section4":
Console.WriteLine("Section 4");
break;
Have a
Dictionary<string,Action<T>>that is keyed bysection. This will completely replace the switch statement.Invoke the corresponding action: