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; } 
4
  • 1
    I think this is your problem: stackoverflow.com/questions/14439231/… "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." Commented Jul 13, 2019 at 6:57
  • 1
    Do you really need the parameter-less constructor? Commented Jul 13, 2019 at 6:57
  • 1
    Even if you remove the issued line, this is still stack overflow, TimerData constructs itself infintely. Commented Jul 13, 2019 at 6:59
  • 1
    Consider also to avoid the ctor with Parameter par having a defalult value, you have the default parameterless ctor for that Commented Jul 13, 2019 at 10:53

1 Answer 1

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); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I just forgot that I don't need constructor Parameters() when I have Parameters(TimerData td = null)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.