Reputation: 91
Okay, I have made another program to be a bit clearer about my problem. I have an object array containing int arrays and I am trying to print the index[0] from the element neuron one. However, I am getting a null reference exception at the line 'Console.WriteLine(ex.neuron[0])' My code is below.
namespace ConsoleApplication5
{
class Program
{
static void Main()
{
ex ex = new ex();
int[]neuron1 = new int[5];
int[]neuron2 = new int[5];
int[]neuron3 = new int[5];
int[]neuron4 = new int[5];
int[]neuron5 = new int[5];
object[,] array1 = new object[2,2];
array1[0, 0] = ex.neuron1;
neuron1[0] = 1;
array1[0, 1] = neuron2;
neuron2[1] = 1;
test(array1);
}
static void test(object[,] array1)
{
ex ex = new ex();
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
}
}
I have a class getting and setting neuron1 here:
static void test(object[,] array1)
{
ex ex = new ex();
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
}
}
I think that the exception is occurring as I am accessing ex.neuron[0] before it has been defined as containing the value one. So my question is how do I access ex.neuron[0] after is has been set as holding the value one. Thanks.
Upvotes: 0
Views: 213
Reputation: 107498
You're creating a new instance of ex
in each function, when you probably just need to pass it along instead. Also, you never set up the neuron
fields on the instance itself. Here is a simplified version of your code:
static void Main()
{
// define it here
ex ex = new ex();
// initialize the neuron fields (although you should probably do this
// in the constructor for ex
ex.neuron1 = new int[5];
ex.neuron2 = new int[5];
ex.neuron3 = new int[5];
ex.neuron4 = new int[5];
ex.neuron5 = new int[5];
// set some neuron array values
ex.neuron1[0] = 1;
ex.neuron2[1] = 1;
// pass the instance along to test
test(ex);
}
static void test(ex ex)
{
// access the array value here
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
Upvotes: 1
Reputation: 5785
you never set ex.neuron1, replace these lines
int[] neuron1 = new int[5];
with
ex.neuron1 = new int[5];
Upvotes: 1