How to use the value of a variable to access a class property in c#?

i have a class like this :

public class Wallet
{
    public int Id { get; set; }

    public decimal Doge { get; set; }

    public decimal Bitcoin { get; set; }

    public decimal Ethereum { get; set; }

    public decimal Tether { get; set; }
}

When the user makes a request for withdrawal or deposit, I have to check the type of currency with the switch case statement and perform the operation. Like this:

private static void CalculateOrder(Order order, Order offer, bool isBuy, string coin)
{
    var sign = -1;
    if (isBuy)
        sign = 1;

    switch (coin)
    {
        case SC.Ethereum:
            {
                order.ApplicationUser.Wallet.Ethereum += sign * (order.Amount);
                offer.ApplicationUser.Wallet.Ethereum -= sign * (order.Amount);
                break;
            }
        case SC.Bitcoin:
            {
                order.ApplicationUser.Wallet.Bitcoin += sign * (order.Amount);
                offer.ApplicationUser.Wallet.Bitcoin -= sign * (order.Amount);
                break;
            }
        case SC.Doge:
            {
                order.ApplicationUser.Wallet.Doge += sign * (order.Amount);
                offer.ApplicationUser.Wallet.Doge -= sign * (order.Amount);
                break;
            }
    }
}

I’m sure the value of the coin variable is the same as the wallet class properties.

Now how can I directly access one of the properties of the same name with a variable value of coin without switch statement ?

In JavaScript, if we have an object like this :

const restaurant = {

  name: 'Classico Italiano',

  openingHours: {
    thu: {
      open: 12,
      close: 22,
    },
    fri: {
      open: 11,
      close: 23,
    },
    sat: {
      open: 0, // Open 24 hours
      close: 24,
    },
  },

};

we can access to opening days like below :

const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

for (const day of days) {
  const open = restaurant.openingHours[day] ?? 'closed';
  console.log(`On ${day}, we ${open}`);
}

Or something like what is said in this post

Is there such a thing in C #?

Answer

The same way you would in javascript. You make the Wallet a dictionary that uses a string as an index, and returns a decimal.

It would probably be better if you used an enumeration instead of a string though.

public enum CoinTypes { Etherium, Bitcoin, Doge };
public class Wallet {
  public int id {get;set;}
  public Dictionary<CointTypes,decimal> Coins {get;set;} = new Dictionary<CoinTypes,decimal>();
}
private static void CalculateOrder(Order order, Order offer, bool isBuy, string coin)
{
    var sign = -1;
    if (isBuy)
        sign = 1;
    var c = Enum.Parse(typeof(CoinTypes), coins);
    order.ApplicationUser.Wallet[c] += sign * (order.Amount);
    offer.ApplicationUser.Wallet[c] -= sign * (order.Amount);
}