Search code examples
c#getsetgetter-setter

How to change value in getter using C#?


So I'm trying to create a program which reads input from the user. Once the inputs are submitted, it needs to return some data but it always returns 0 for each value.

Let's say that I'm asking the user to enter 5 inputs:

firstPaychek, secondPaycheck, finanancialAid, allowances and tips.

I also created those variables to 0.0 since all of them are double. Here it is the setter and getter of firstPaycheck

private double payCheckOne = 0.0;
private double payCheckTwo = 0.0;
private double financialAid = 0.0;
private double allowance = 0.0;
private double TIPS = 0.0;

public double checkOne {
    get { return (payCheckOne / 12); }
    set { payCheckOne = value; }
}

Now, let' say that I would like to return the addition of every value:

public void getTotalIncome() {
    double totalIncome = (payCheckOne + payCheckTwo + financialAid + allowance + TIPS);
    Console.WriteLine("------------ Total Income ------------");
    Console.WriteLine(totalIncome);
    Console.WriteLine("--------------------------------------");
}

I would like to say, that all the blocks of code above belong to an Income class. I'm trying to use them in a class called Expenses and from there I'm calling the getMonthly method in my main class.

Here it is my repl.it: https://repl.it/@KevinAzuara/Testing


Solution

  • The thing is that you're obtaing the values from the wrong income (one that you're not setting the values for). I'd suggest you to pass in the income object instead of initializing inside the Expenses class. Something like this:

    public void getMontlyExpenses(Income inc) {
        //...
    }
    

    And remove the declaration

    Income inc = new Income();
    

    Then you can call it like

    exp.getMontlyExpenses(inc); // which is the right Income object
    

    That's what I think your problem is.