I have come across the following piece of code
if (Region.Current == Region.EU)
{
return RegionalPriceLN;
}
else if (Region.Current == Region.NY)
{
return RegionalPriceNY;
}
else if (Region.Current == Region.HK)
{
return RegionalPriceHK;
}
else if (Region.Current == Region.TK)
{
return RegionalPriceTK;
}
return null;
And want to refactor it to use a Dictionary. Was thinking of something like below:
return Map.TryGetValue(Region.Current, out func) ? func() : null;
And the dictionary being initialized like this:
Map = new Dictionary<Region, Func<double?>>
{
{Region.EU, () => RegionalPriceLN},
{Region.NY, () => RegionalPriceNY},
{Region.HK, () => RegionalPriceHK},
{Region.TK, () => RegionalPriceTK}
};
Another approach, to optimize memory usage would be to hold a static dictionary instead of an instance one:
private static readonly Dictionary<Region, Func<TickingBasket, double?>> Map = new Dictionary<Region, Func<TickingBasket,double?>>
{
{Region.EU, t_ => t_.RegionalPriceLN},
{Region.NY, t_ => t_.RegionalPriceNY},
{Region.HK, t_ => t_.RegionalPriceHK},
{Region.TK, t_ => t_.RegionalPriceTK}
};
This would require for us to pass "this" to the delegate:
return Map.TryGetValue(Region.Current, out func) ? func(this) : null;
Can you think of a more elegant way to do this?
Regards.
UPDATE: Region is a reference type.