Search code examples
c#constructorgetter-setter

C# update fields using another field's setter


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?


Solution

  • 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);
        }
    }