0

I have two classes and I need them to make instances of each other. To preevent stack overflow exception I use constructors with parameters. But how can I call them? I can call only basic constructors.

public class TimerData : INotifyPropertyChanged
{
    public TimerData()
    {
        //parameters = new Parameters();
    }

    public TimerData(Parameters pr = null)
    {
        parameters = pr ?? new Parameters(this);
    }

    // Here I create an instance of the TimerData class to call the constructor 
    // with parameters through it. It gives an error that the field initializer 
    // cannot access a non-static field
    TimerData timerData = new TimerData();
    private Parameters parameters = new Parameters(timerData);
}


public class Parameters : INotifyPropertyChanged
{
    public Parameters()
    {
        //timerData = new TimerData();
        //timerData.EventSecondsNotify += DecreaseFatigue;
        //timerData.EventSecondsNotify += DecreaseSatiety;
    }

    // How to call this constructor?
    public Parameters(TimerData td = null)
    {
        timerData = td ?? new TimerData(this);
        timerData.EventSecondsNotify += DecreaseFatigue;
        timerData.EventSecondsNotify += DecreaseSatiety;
    }

    private TimerData timerData;
}
Amazing User
  • 3,473
  • 10
  • 36
  • 75
  • 1
    I think this is your problem: https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property "You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that timerData will be initialized before parameters, so the above line might throw a NullReferenceException." – grabhints Jul 13 '19 at 06:57
  • 1
    Do you really need the parameter-less constructor? – Sohaib Jundi Jul 13 '19 at 06:57
  • 1
    Even if you remove the issued line, this is still stack overflow, `TimerData` constructs itself infintely. – shingo Jul 13 '19 at 06:59
  • 1
    Consider also to avoid the ctor with Parameter par having a defalult value, you have the default parameterless ctor for that – Gian Paolo Jul 13 '19 at 10:53

1 Answers1

2

I don't get why you are initializing the instances outside of your constructor. This should work fine:

public class TimerData
{
  private Parameters parameters;
  public TimerData(Parameters pr = null)
  {
    parameters = pr ?? new Parameters(this);
  }
}
public class Parameters
{
  private TimerData timerData;
  public Parameters(TimerData td = null)
  {
    timerData = td ?? new TimerData(this);
  }
}
Sohaib Jundi
  • 1,576
  • 2
  • 7
  • 15