1

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.

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

1 Answer 1

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

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.