0

I want to create a dynamic jagged array with dynamic data. The problem is that a part of the jagged array is only a two column type and the rest of it is a 4 column type. Code is in C#.

public static Object[][] my_array = new Object[20][];
public static void LoadData()
{
     for(int i = 0; i < 20; i++)
     {
         my_array[i]    = new Object[20];
         my_array[i][0] = "Data1";
         my_array[i][1] = "Data2";
         my_array[i][2] = "Data3";
         my_array[i][3] = "Data4";
         my_array[i][4] = new Object[100];

         for(int j = 0; j < 100; j++)
         {
             my_array[i][4][j] = new Object[200];
             my_array[i][4][j][0] = "SubData1";
         }
         my_array[i][5] = "Data6";
     }
 }

I get following error:

Severity Code Description Project File Line Suppression State Error CS0021 Cannot apply indexing with [] to an expression of type 'object'

Is this even possible to do this in C#?

9
  • Rather than arrays, I suggest you use List<T> structures, they will give you dynamic flexibility. If you have elements of different types, then maybe you should use a class with typed and named members. Commented Jun 25, 2018 at 8:30
  • The compiler does not know that my_array[i][4] is an Object[] instance, you have to cast it Commented Jun 25, 2018 at 8:31
  • 2
    This seems more like a XY problem. What problem are you actually trying to solve? What you are trying seems pretty dangerous because sometimes at my_array[i][j] is a string and sometimes there is another object[]. Do you want to parse some kind of JSON or XML? Because there are parsers for that. Commented Jun 25, 2018 at 8:32
  • 2
    This smells of using arrays to avoid defining a class. Commented Jun 25, 2018 at 8:33
  • I love the smell of xy when i get home from work, as @bommelding said just define some concrete classes uses list<T> where its needed, and make your life easier Commented Jun 25, 2018 at 8:40

1 Answer 1

2

You should cast it to Array before applying indexing, like:

var array = (Object[]) my_array[i][4];
Sign up to request clarification or add additional context in comments.

2 Comments

Using my example where I should put this?
@JonZ for(int j = 0; j < 100; j++) { var array = (Object[]) my_array[i][4]; array[j] = new Object[200]; var mySecondArray = (Object[])array[j]; mySecondArray[0] = "SubData1"; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.