I am developing one console application using C#. I need to call different-2 get APIs based on the input provided by the user and write the response on console.
So if user enters 1, I need to call a group weather api. If user enters 2 then I need to call temperature API. If user enters 3 then call some other API and if enters other then this just write invalid input.
For now I have just written multiple if
and else if
. Is there any better approach? Because this way there are multiple if else. And same goes for switch case as well.
I have also thought of creating mapping of input the endpoint like defining them in config file and then read into a dictionary.
So in future it can support below things.
if I need to call another API for input 4….. or No need to call any API for input 2. Or call different API on input 2.
CodePudding user response:
well one way around this is to use Dictionary and Action :
private static readonly Dictionary<string, Action> MyApiCalls= new()
{
{
"1", () =>
{
Console.WriteLine("im cool");
}
},
{
"2", () =>
{
Console.WriteLine("im really cool");
}
}
};
and you use it like this :
static void Main(string[] args)
{
var input = Console.ReadLine() ?? "1";
MyApiCalls[input]();
Console.ReadKey();
}
so the action can be your api call or anything else.
CodePudding user response:
if the number of cases is limited, I suggest to stick to a switch (cleaner then if-else in my opinion). A switch doesn't cost anything in speed.
Happy programming!