Results 1 to 3 of 3

Thread: Multidimensional Arrays of Objects

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2001
    Location
    Austin, TX
    Posts
    77

    Multidimensional Arrays of Objects

    I'm interested in creating a large 2-dimensional array of (custom) objects. I'd like to call the constructor of each object with the x and y index of its array position. For a small 2D array, this would look something like:

    Code:
    Cell[,] cells = new Cell[2,2] {{new Cell(1,1), new Cell(2,1)}, {new Cell(2,1), new Cell(2,2)}};
    (Where Cell is a custom class that accepts two int parameters to its constructor.)

    That's all fine and well but what if I want to create a LARGE array of objects (say, 100 in each dimension) and I want to call the constructor on each array element? It would be impractical to use the above notation (i.e. explicitly declare each Cell) but I don't know how else to create the array. Moreover, that approach wouldn't work if I didn't know the exact size of the array at design time (which I don't).

    ArrayList seems like it would work but it only handles single dimensions. I suppose an ArrayList of ArrayLists might work but it seems like a cleaner solution is out there...

  2. #2
    Member
    Join Date
    Sep 2004
    Posts
    60

    Re: Multidimensional Arrays of Objects

    Have you thought of using Vectors?

    A vector is dynamic and can store classes of your own creation

  3. #3
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428

    Re: Multidimensional Arrays of Objects

    umm ok I wrote two examples. One is for regular arrays like you used, and one for jagged arrays, whichever that would be more useful in your case. I used the Button class, you can replaced that with your class. Also you can reaplce the array size, 100, with a variable

    Code:
    Button[,] btn= new Button[100,100];
    			for (int i=0; i<100; i++)
    				for (int j=0; j<100; j++)
    				{
    					btn[i,j]= new Button();
    				}
    
    
    
    			Button[][] btn2 = new Button[100][];
    			for (int i=0; i<100; i++)
    			{
    				btn2[i] = new Button[100];
    				for (int j=0; j<100; j++)
    				{
    					btn2[i][j]= new Button();
    				}
    			}
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width