Arrays of Arrays

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



Answer this question

Arrays of Arrays

  • Bùi Duy Hiếu

    Hi Tom,

    Thanks much.

    Looks like a basic gaff on my end.

    Jeff


  • JohnRM2

    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.



  • Yashraj

    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



  • Eric Tsai

    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


  • Arrays of Arrays