I’m getting “reference to an object was not set for an instance of the object” run-time error with the suggestion: “Use the new keyword to create an object instance.
But I don’t understand what I’m doing wrong.
There is my code:
int numListas = 10;
x = 15;
int[][] listas;
listas = new int[numListas][];
Random random = new Random(); // generate random number
for (idx = 0; idx < numListas; idx++)
{
int idx_el;
for (idx_el = 0; idx_el < x ; idx_el++)
{
listas[idx][idx_el] = random.Next(0,100);
}
}
This line:
declares a variable which is a reference to an array of arrays.
This line:
initializes the variable to refer to an array of
numListasarray references… but each of those “subarray” references is null to start with. You need to initialize each “subarray”, probably in your outer loop:Note that an alternative is to use a rectangular array instead of an array of arrays:
As an aside, code generally reads more clearly when you declare and initialize variables together, rather than declaring them earlier and then initializing them later. Also, underscores in C# variable names aren’t terribly idiomatic, and the overall variable names aren’t terribly clear. I’d write your code as:
You should also consider initializing a single
Randominstance outside the method and passing it in – see my article onRandomfor more information.