-4

I have a jagged array that contains other 1d string arrays:

string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};

When I try to get the sub-arrays, they give a null value (I might be doing something wrong):

foreach (string[] arr in jagged[][]) {
    // My stuff here
}

Did I do something wrong in the array initialization progress or do I have to convert the sub-arrays somehow?

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
KonaeAkira
  • 236
  • 1
  • 11
  • 5
    what specific code is causing what specific error? (yes you might be doing something wrong but how will we know if you don't show what you're doing?) – Don Cheadle Aug 05 '16 at 19:39
  • 1
    Just out of curiosity: why are you using arrays like this when .NET has so many better, easier-to-use options for collections of things? It's a full-featured, object-oriented programming language, not a scripting language. Take advantage of that. – rory.ap Aug 05 '16 at 19:39
  • 3
    Does that even compile? `foreach (string[] arr in jagged[][])` doesn't look like valid syntax. – sstan Aug 05 '16 at 19:42
  • 3
    Can you post that brings you null? because this doesn't compile - `... in jagged[][]..` – Gilad Green Aug 05 '16 at 19:42
  • For sure `in jagged[][]` is invalid – Kovpaev Alexey Aug 05 '16 at 19:45

3 Answers3

1

Just the foreach part is wrong. I have tested it like as follows:

string[] first = { "one", "two" };
string[] second = {"three","four"};
string[][] jagged = {first,second};

foreach (string[] arr in jagged)
{
    Console.WriteLine(string.Join(",", arr));
}

Output:

one, two

three, four

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Henrique Forlani
  • 1,325
  • 9
  • 22
0

It should be:

foreach (string[] arr in jagged)
{
    // My stuff here
}

I pasted your code on my local environment and could iterate just fine.

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

If you use jagged[][] in your loop, then possibly you get a type conversion failed message:

Cannot convert type 'char' to 'string'.

Instead use jagged in your loop.

public class Program
{
    public static void Main()
    {
        string[] first = {"one","two"};
        string[] second = {"three","four"};
        string[][] jagged = {first,second}; 

        foreach (string[] arr in jagged)
        {
            //Your code
        }
    }
}
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32