Here is my code below:
public interface IResponseEntity
{
}
public class ResponseEntity : IResponseEntity
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
public class ObjectForRequest
{
public string abcd { get; set; }
public string xyz { get; set; }
public string pqrs { get; set; }
public short mnop { get; set; }
}
private async Task<IResponseEntity> Dowork_for_A(ObjectForRequest objReq)
{
//Code for A
....................
}
private async Task<IResponseEntity> Dowork_for_B(ObjectForRequest objReq)
{
//Code for B
....................
}
private async Task<IResponseEntity> Dowork_for_C(ObjectForRequest objReq)
{
//Code for C
....................
}
private async Task<IResponseEntity> Dowork_for_D(ObjectForRequest objReq)
{
//Code for D
....................
}
public async Task<IResponseEntity> method(ObjectForRequest objReq)
{
if (CONFIGVALUE == 'A')
return await Dowork_for_A(RequestOBJ);
else if (CONFIGVALUE == 'B')
return await Dowork_for_B(RequestOBJ);
else if (CONFIGVALUE == 'C')
return await Dowork_for_C(RequestOBJ);
else if (CONFIGVALUE == 'D')
return await Dowork_for_D(RequestOBJ);
else
return null;
}
As if now I am checking config value in the if condition and then calling async task to return value.
How can I setup <key, value> pair of dictionary as config value as 'key' and 'value' as async task? Or in other words here how can I store async task in a dictionary and call them according to config value?
This is very straightforward. Declare your dictionary as such:
Dictionary<char, Func<ObjectForRequest, Task<IResponseEntity>>> _actions =
new Dictionary<char, Func<ObjectForRequest, Task<IResponseEntity>>>()
{
{ 'A', Dowork_for_A },
{ 'B', Dowork_for_B }
// ...
}
Then:
public async Task<IResponseEntity> method(ObjectForRequest objReq)
{
Func<ObjectForRequest, Task<IResponseEntity>> action;
if (!_actions.TryGetValue(CONFIGVALUE, out action))
{
return null;
}
return await action(objReq);
}
Also, please do consider the performance implications of this. Dictionary's are wicked fast for large sets, but if you really do only have 3 or 4 options, a switch or if ... else chain is almost certainly going to be faster. What the exact tipping point is when Dictionary becomes better is hard to say.