Reputation: 3563
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;
}
Upvotes: 0
Views: 387
Reputation: 1664
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);
}
}
Upvotes: 2