user225626
user225626

Reputation: 1099

2 dimensional array in C#

Can the second dimension be initialized as dynamically sizeable?

Upvotes: 3

Views: 5343

Answers (5)

Bashar Alibrahim
Bashar Alibrahim

Reputation: 1

if you want to create 2 dimensional array in C# each element type is bitmap

int num1 = 10,num2 = 20;
Bitmap[][] matrix= new Bitmap[num1][]; 
for (int i = 0; i < num1; i++ )
     matrix[i] = new Bitmap[num2];

Upvotes: 0

Kees C. Bakker
Kees C. Bakker

Reputation: 33371

Normally a jagged array has a size. You could use two collections:

List<List<int>> list = new List<List<int>>();

You can access the values the same way you would access any array. The advantage is that you don't need to specify the size at creation.

Edit: if the "outer" array is fixed, you could use:

List<int>[] list = new List<int>[100]();

Edit: looking to your example I'd say something like this could do the trick:

List<int>[] sVertRange = new List<int>[924];

int nH = 0;
for (int h = 315; h < 1240; h++) 
{
    for (int v = 211; v <= 660; v++) 
    {
            Color c = bmp.GetPixel(h, v);
            if (c.R > 220 && c.G < 153) 
        {
            if(sVertRange[nH] == null)
            {
                sVertRange[nH] = new List<int>();
            }

                    sVertRange[nH].Add(v);
            }
            nH++;
        }
}

Upvotes: 1

user225626
user225626

Reputation: 1099

UPDATE: I just tested this and it doesn't work--it crashes immediately. So how is the following written in Kees's syntax?

    int[][] sVertRange = {new int[924] ,new int[]{}};  
    int nH = 0;
    int nV = 0;
    for (int h = 315; h < 1240; h++) {
        for (int v = 211; v <= 660; v++) {
            Color c = bmp.GetPixel(h, v);
            if (c.R > 220 && c.G < 153) {
                sVertRange[nH][nV++] = v;
            }
        nH++;
        }
    }

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74177

You mean a jagged array? Like this:

class Program
{
  public int[][] jaggedArray = {
                                 new int[]{ 1 } ,
                                 new int[]{} ,
                                 new int[]{ 1 , 2 , 3 } ,
                               } ;
}

Upvotes: 4

Andrew Hare
Andrew Hare

Reputation: 351456

No (since C# array dimensions are fixed), but you could create an array of List<T>.

Upvotes: 6

Related Questions