How to reference a variable in method parameter?

Suppose I have this class:

public class Potion(){

public int WaterAmount;
public int ReagentAmount;

}

Now if I wanted a method to check the amount of water or the amount of reagent in the potion I would have:

public int GetWaterAmount ( Potion pot ){

return pot.WaterAmount;

}
public int GetReagentAmount ( Potion pot ){

return pot.ReagentAmount;

}

Now my question is how can I combine these 2 methods into one so that I can just enter the parameter of the liquid I want to check for? Heres some wrong syntax of what I was looking for:

public int GetAmount ( Potion pot, int SelectedLiquid){

return pot.SelectedLiquid;

}

void main(){

GetAmount(pot, WaterAmount);
GetAmount(pot, ReagentAmount);
}

In essence how can I make a parameter (selectedliquid) refer to different variables in a class (wateramount or reagentamount) ?

Or is this not possible and I do need to have 1 method for each variable I want to check for?

is “type” what Im looking for?

You can create an enum to represent the different liquid types.

public enum LiquidType
{
    Water,
    Reagent
}

Then the most straight-forward way to implement GetAmount with LiquidType as a parameter would be to use a simple switch statement to figure out which field in Potion represents which liquid type.

public static int GetAmount(Potion potion, LiquidType liquidType)
{
    switch(liquidType)
    {
        case LiquidType.Water:
            return potion.WaterAmount;
        case LiquidType.Reagent:
            return potion.ReagentAmount;
        default:
            throw new IndexOutOfRangeException();
    }
}

One downside however of using switch statements like this a lot in your code is that every time you introduce a new element to the enum, you’ll need to go modify all the switch statements all around your codebase and add the case for the new element, and you could easily forget to do this in some places.

Alternatively you could create a new struct that contains both the liquid type and the amount, and do something like this:

[Serializable]
public struct Liquid
{
    public LiquidType liquidType;
    public int amount;
 
    public Liquid(LiquidType setLiquidType, int setAmount)
    {     
        liquidType = setLiquidType;
        amount = setAmount;
    }
}

[Serializable]
public class Potion
{
    public Liquid[] contents = new[]
    {
        new Liquid(LiquidType.Water, 5),
        new Liquid(LiquidType.Reagent, 2)
    };
 
    public int GetAmount(LiquidType liquidType)
    {
        foreach(var element in contents)
        {
            if(element.liquidType == liquidType)
            {
                return element.amount;
            }
        }
        return 0;
    }
}
1 Like

That’s what I was looking for, thanks!

1 Like