locked
Arrays of Arrays RRS feed

  • Question

  • Hi,

    I have a class that is really just a struct. And I create an arrays of these, and write into them,

    Ex,

    public class Modules

    {

      public string[] name = new string[16];

      public string[] number = new string[16];

      public string[] state = new string[16];

    }

    Modules[] aModule = new Modules[16];

    This gives a runtime error,

    aModule[0].name[0] = "SomeData";

    Using C++ stlye, maybe it cannot be done this way.

    Any help would be appricated.

    Thanks

    Jeff

     

    Monday, June 12, 2006 4:53 PM

Answers

  • Jeff,

    You created an array of Modules with:


    Modules[] aModule = new Modules[16];
     

    but you need to initialize the array elements before you try to access them:


    for (int j = 0; j < 16; j++)
    {
        aModule[j] = new Modules();
    }

     

    You're running into problems because the elements of the array are all null by default.

    -Tom Meschter
    Software Dev, Visual C# IDE

    Monday, June 12, 2006 5:42 PM

All replies

  • Jeff,

    You created an array of Modules with:


    Modules[] aModule = new Modules[16];
     

    but you need to initialize the array elements before you try to access them:


    for (int j = 0; j < 16; j++)
    {
        aModule[j] = new Modules();
    }

     

    You're running into problems because the elements of the array are all null by default.

    -Tom Meschter
    Software Dev, Visual C# IDE

    Monday, June 12, 2006 5:42 PM
  • Hi Tom,

    Thanks much.

    Looks like a basic gaff on my end.

    Jeff

    Monday, June 12, 2006 5:50 PM
  • If this is really a struct, then mark it as a struct and you won't have to worry about constructing the array elements.

    The reason you have this bug is because classes are referenced based objects which means that they need to be constructed before being used.

    Structs are value based objects and don't need to be constructed because they are integers, characters, etc.

    Friday, June 16, 2006 5:13 PM
  • Hi,

    Thats a good point. I started it as a struct, and then changed it to a class. I might have to do some data access st some point.

     

    Thanks

    Jeff

    Monday, June 19, 2006 12:34 PM