C# new comer question about System.NullReferenceException

  • Thread starter Thread starter msnews.microsoft.com
  • Start date Start date
M

msnews.microsoft.com

actaully the code i have written below is pretty simple and short. no
idea why it terminate at run-time with "An unhandled exception of type
'System.NullReferenceException' occurred"

Thank you

---code below---

using System;

class ANN
{
private int size;
private N[] nodes;

public ANN (int size)
{
this.size = size;
nodes = new N[size];
for ( int i = 0 ; i < size; i++)
{
nodes.GetType(); /*An unhandled exception of type
'System.NullReferenceException' occurred*/
}

}

static void Main()
{
ANN ann = new ANN(2);
}
};

class N
{
private int connectionCount;
private int [] connected;
private double [] weight;
private double bais;

public N() {
}

};
 
Hi,

When you create the node array it will be filled with empty references
(null), so when you call (null).GetType() you get the
NullReferenceException, because you are trying to do something with
nothing (null).

You need to not only set the size of a reference array, but you need to
set each value to something meaningfull before you can use it (new N()).

For numerical arrays the empty value is, 0 so you can still use it without
getting an exception.


Happy coding!
Morten Wennevik [C# MVP]
 
Back
Top