Part of variable name has to be dynamic

75 Views Asked by At

I want dynamicVariable below to hold different name each time

 Price.dynamicVariable.Item1 

Data.cs:

namespace ProjectName.Shared.Price
{
    public class Price
    {
        
            public static readonly Tuple<double?, double?> applePrice = new Tuple<double?, double?>(2, 10);

            public static readonly Tuple<double?, double?> bananaPrice = new Tuple<double?, double?>(1, 2);

           public static readonly Tuple<double?, double?> orangePrice = new Tuple<double?, double?>(2, 4);

    }

}
 

ItemComponent.cs:

using ProjectName.Shared.Price   

// I will be getting `ID` as "applePrice", "bananaPrice" or "orangePrice" dynamically
Id = dynamicVariable  
    
    // how to substitute ID below with dynamic ID's based on what we receive
    Min = Price.ID.Item1 
    Max = Price.ID.Item2
    
If Id passed was "bananaPrice", I expect ID to hold "bananaPrice".So, it will become
    
    Min = Price.bananaPrice.Item1 // so that value received would be 1 (from Data.cs)
    Max = Price.bananaPrice.Item2 // value received would be 2

May I know how I can achieve this. Thank you.

1

There are 1 best solutions below

1
JonasH On BEST ANSWER

The way to do things like this is to make the code more abstract so you do not have to fiddle around with anything 'dynamic'. For example by using a dictionary and a enum:

public enum Fruit{banana, apple, orange}

public Dictionary<Fruit, (decimal? Min, decimal? Max)> Price = new (){...}

public double? GetMinPrice(Fruit fruit) => Price[fruit].Min;

If you need to convert a string to a fruit, see enum.TryParse. For more serious use cases you should consider using a database.