arrays and constructors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Todd Smith

    #1

    arrays and constructors

    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() );
    }
    }
  • Mattias Sjögren

    #2
    Re: arrays and constructors

    Todd,
    [color=blue]
    >So how do I initialize an array of
    >objects, calling all the constructors for each thing in the array?[/color]

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



    Mattias

    --
    Mattias Sjögren [MVP] mattias @ mvps.org

    Please reply only to the newsgroup.

    Comment

    • Jason Smith

      #3
      Re: arrays and constructors

      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.


      "Todd Smith" <smittod@auburn .edu> wrote in message
      news:ed3092e7.0 310141251.66833 529@posting.goo gle.com...[color=blue]
      > 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() );
      > }
      > }[/color]


      Comment

      Working...