2

first time posting. I'm a bit of a C# beginner and am having a bit of trouble setting values to a multi-dimensional array. The array is held in one class and I'm trying to set the values from another class. The problem I can't work out is how to initialize the array variable from the other class? In one class (GRID) I have:

public float[,] values;

then in another class i try to reference the array using a class object (grid) like this:

GRID grid = new GRID();
this.lblFirstVal.Text = "First Value (0,0): " + grid.values[0, 0];

and I get an error on the grid.values[0,0] part of the code: Object reference not set to an instance of an object.

Still a bit new to OO programming so I've probably not understood something properly, but I can't for the life of me work this one out. Thanks in advance for any help!

1 Answer 1

1

Make sure you initialize the values array appropriately, either by using a field initializer:

public float[,] values = new float[1, 1];    // new 1 by 1 array

Or by setting the value of the field in the constructor:

public float[,] values;

public GRID() {
    this.values = new float[1, 1];           // new 1 by 1 array
}

Or you can set the value of the field externally:

GRID grid = new GRID();
grid.values = new float[1, 1];               // new 1 by 1 array
this.lblFirstVal.Text = "First Value (0,0): " + grid.values[0, 0];

Of course, you may want to set the width an height to something other than 1.

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

1 Comment

Thanks very much, I used the last option and set the value of the field externally. Working properly now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.