0

I have a class Fuel1:

class Fuel1
{
    public double Temperaure                 
    {
        get { return Temperaure; }
        set
        {
            Temperaure = value;
            initialize(Temperaure);
        }
    }

    public double Cp { get; private set; }  // J/mol.K
    public double H { get; private set; }  // J/mol

    public Fuel1(double Temperaure)
    {
        this.Temperaure = Temperaure;
        initialize(Temperaure);
    }

    private double calculate_cp(double te)
    {
        // calculate Cp
    }

    private double calculate_h(double te)
    {
        // calculate H
    }

    private void initialize(double temperature)
    {
        H = calculate_h(temperature);
        Cp = calculate_cp(temperature);
    }
}

The class is initialized with temperature like this:

var fuel = new Fuel1(1000.0);

and then Cp and H fields are set in initialize method. I want to update the values of H and Cp automatically when I update the value of the T using the setter. For example I set the temperature to 1200.

fuel.Temperature = 1200.0;

I expect Cp and H to update. However putting the initialize method in the setter causes an infinite loop. How should I do this without running into an infinite loop?

MehdiB
  • 870
  • 12
  • 34
  • When you debug through the code, why is it going into an infinite loop? – mjwills Jun 08 '18 at 21:34
  • 1
    You are setting `T` inside the setter for `T`; that's why it's an infinite loop. Use a private field, e.g., `private double t;` and set/get that value. – Heretic Monkey Jun 08 '18 at 21:35
  • Also, a bit of nomenclature here: `T` is a **property** (it has a getter and/or setter). A **field** is variable defined at the class level, with no getter or setter. – Heretic Monkey Jun 08 '18 at 21:37
  • I updated the question and changed the property name. – MehdiB Jun 08 '18 at 21:43

1 Answers1

0

This is crazy. This is circular

public double T                 
{
    get { return T; }
    set
    {
        T = value;
        initialize(T);
    }
}

You need a backing field

private double t;
public double T                 
{
    get { return t; }
    set 
    {    
        t = value;
        initialize(t);
    }
}
paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • first I downvoted because you posted an answer but there was no answer in it. you had just mentioned the problem which I already knew. Now I up voted because you posted a simple and correct answer. thanks. – MehdiB Jun 08 '18 at 22:00
  • @MehdiB Did you also down vote the now deleted answer from Sach? – paparazzo Jun 08 '18 at 22:03