[Mono-list] Matrix of Objects

Jonathan Pryor jonpryor@vt.edu
Thu, 03 Mar 2005 07:07:46 -0500


On Wed, 2005-03-02 at 22:30 +0000, Phillip Neumann wrote:
> Hello...
> 
> I wonder how to work with arrays of objects.

<snip/>

> when executing i get:
> System.NullReferenceException: Object reference not set to an instance 
> of an object
> 
> how shall i create my matrix?

Your example is equivalent to this:

	string[] array = new string[10];
	array[0].Length;	// throws NullReferenceException

The above will also generate a NullReferenceException.  The reason is
because the array is separate from the objects it contains; you created
an array, but never put anything in it.

The correct approach would be this:

	// create array
	string[] array = new string[10];

	// populate
	for (int i = 0; i < array.Length; ++i)
		array[i] = "some string" + i.ToString();

	// access array
	int total_length = 0;
	for (int i = 0; i < array.Length; ++i)
		total_length += array[i].Length;

Or for your matrix code in the Terreno constructor:

	// create matrix
	_Matrix = new Celda[px,py];

	// populate matrix
	for (int i = 0; i < px; ++i)
		for (int j = 0; j < py; ++j)
			_Matrix[i, j] = new Celda ();

 - Jon