hi I'm writing some code where I have made a few methods and have put all of them in a list however I want the user to be able to choose a method from the list and then run that method with out writing a very long if statement what i have so far
using System;
namespace MyApplication
{
class program
{
//arrays
static void Arrays()
{
Console.WriteLine("Enter number of cars:");
Console.ReadKey();
}
// List
static void List()
{
Console.WriteLine("Enter items for shopping list");
shoppingList.Add("Apples");
shoppingList.Add("oranges");
shoppingList.Add("milk");
shoppingList.Add("butter");
Console.ReadKey();
}
static void Main(string[] strings)
{
List<Action> methods = new List<Action>();
methods.Add(Arrays);
methods.Add(List);
Console.WriteLine("what method do you want:");
string answer = Console.ReadLine();
foreach (Action a in methods.Where(//one of the methods == answer));
Console.WriteLine(//the method that is == answer);
if (answer == //one methods in list)
{
Console.WriteLine(////the method that is == answer);
}
}
}
}
CodePudding user response:
You could use a dictionary:
Dictionary<string, Action> methods = new(StringComparer.OrdinalIgnoreCase);
methods.Add(nameof(Arrays), Arrays);
methods.Add(nameof(List), List);
Console.WriteLine("what method do you want:");
string answer = Console.ReadLine();
if(methods.TryGetValue(answer, out Action doIt))
{
doIt();
}