0

I am using multiple classes, and my "ControllerCLass" needs to initialise a "ListManager" class. Since some of the parameters are only used once in the ListManager and multiple times in the ControllerClass I thought I would initialise them in the Controller and give them to the Manager.

I could obviously hard code this stuff but I only want to have this in one place so changing it is just 5 keystrokes and not looking for it in multiple classes.

My controller, or the relevant part of it:

    public class ControllerClass
    {
        int growthRate = 50;
        int startLength = 500;
        ListManager listManager = new ListManager(startLength, growthRate);

        /* Starts the Gui */
        public void RunProgram()
        {
            Application app = new Application();
            app.Run(new MainWindow(this)); 
        }
...}

Then the ListManager:

    public class ListManager
    {
        int _startLength;
        int _growthRate;

        public ListManager(int startLength, int growthRate)
        {
            _startLength = startLength;
            _growthRate = growthRate;
        }
...}


What I want is for it to work, and if I replace the

ListManager listManager = new ListManager(startLength, growthRate);

with

ListManager listManager = new ListManager(30, 30);

it has no Problems whatsoever. But with it it just tells me I can't reference the non-static field with the field initializer. This must be possible though since I do that all the time, I can just not find out what the problem here is.

bv_Martn
  • 139
  • 12
  • If the values of `growthRate` and `startLength` don't change (during the runtime of the app), why not declare them as `const`? – Corak Apr 29 '19 at 11:47
  • @Corak I might want to add an option later on that the user can change those two to his pleasing – bv_Martn May 02 '19 at 14:22

1 Answers1

2

You cannot use other fields when initializing a field with it's declaration.

You can either move the initialization to a constructor, there you can access the other fields:

public class ControllerClass
{
    int growthRate = 50;
    int startLength = 500;
    ListManager listManager;

    public ControllerClass()
    {
        this.listManager = new ListManager(this.startLength, this.growthRate);
    }

    ...
}

Or repeat the literals:

public class ControllerClass
{
    int growthRate = 50;
    int startLength = 500;
    ListManager listManager = new ListManager(50, 500);

    ...
}
sticky bit
  • 36,626
  • 12
  • 31
  • 42