arrays and constructors

  • Thread starter Thread starter Todd Smith
  • Start date Start date
T

Todd Smith

I have this code, but I get a runtime error that says arr[34] isn't
set to an instance of a class. So how do I initialize an array of
objects, calling all the constructors for each thing in the array?

-thanks
-todd


using System;
using System.Windows.Forms;

class Shape {
public int a;
public Shape() {
a = 1;
}
}

class A : Form {
public A() {
Shape[] arr = new Shape[100];
MessageBox.Show( arr[34].a.ToString() );
}
public static void Main() {
Application.Run( new A() );
}
}
 
Todd,
So how do I initialize an array of
objects, calling all the constructors for each thing in the array?

for ( int i = 0; i < arr.Length; i++ )
arr = new Shape();



Mattias
 
Question: Do you really want "exactly" 100 shapes? If not, why not use a
list or something like that so you can add shapes as you need them, and
remove them from arbitrary places within the list? Or a dictionary, or
something else other than an array, anyway.

It may be better also to check the object for null and handle that in the
code.
 
Back
Top