Ben
Ben

Reputation: 62484

How to specify dynamic default values

New to C# here... trying to figure out how the below new GameObject[20, 20] can actually reference the private property values instead of the hard coded values.

private int xRadius = 20;
private int yRadius = 20;

private GameObject [,] grid = new GameObject[20, 20];

I've tried variations of this.xRadius and self.xRadius with no luck. How can I do this?

Upvotes: 3

Views: 901

Answers (2)

sixones
sixones

Reputation: 1973

You cannot use this in the variable declaration scope of a class because at that moment in time there is no reason for xRadius to be defined before grid.

You can achieve what you want by either declaring xRadius and yRadius as constants (constants are immutable variables which don't change during runtime);

private const xRadius = 20;
private const yRadius = 20;

private GameObject[,] grid = new GameObject[xRadius, yRadius];

Or marking them as static variables (static variables exist outside of any class instance and will available after any class instances disappear);

class Example {
    private static xRadius = 20;
    private static yRadius = 20;

    private GameObject[,] grid = new GameObject[Example.xRadius, Example.yRadius];

Or you could define the grid in your classes constructor and use a normal class variable reference;

class Example {
    public Example() {
        this.grid = new GameObject[this.xRadius, this.yRadius];
    }
}

The fastest solution (in terms of less resource usage at runtime) is using constants as the values will be copied over at compile time and they wont occupy any extra resources, the most dynamic solution is setting them in the constructor or before you access the grid object this would allow you to change xRadius and yRadius at runtime and re-initialise the grid variable using the same radius variables.

Upvotes: 5

jdphenix
jdphenix

Reputation: 15445

Field initializers are not able to access instance members, because they are run in a static context. Thus, they (like static methods) are unable to reference instance methods.

Assuming the containing class is Foo, you can initialize grid in the constructor,

class Foo
{
    private int xRadius = 20;
    private int yRadius = 20;

    private GameObject[,] grid;

    public Foo()
    {
        grid = new GameObject[xRadius, yRadius];
    }
}

Upvotes: 3

Related Questions