Click here to Skip to main content
15,849,129 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to add many int[,] arrays in an arraylist but I couldn't extract them in int[,] data type.
This code will demonstrate what i want to do:

arraylist Myarraylist =new arraylist();
int [,] array1 = new int[3,2];
int [,] array2 = new int[5,2];
int [,] array3 = new int[6,4];


I want this semi-code to happen:

int[,] Myarray1 = Myarraylist[1]

but when i extracted them a problem came up that they are objects not even object[,]
but just object. How can I cast them to int[,] again?

Thank you for your help.
Updated 23-May-11 2:36am

You need to cast the dereferenced element, for instance, the following code will work:
ArrayList Myarraylist = new ArrayList();
    int [,] array1 = new int[3,2];
    int [,] array2 = new int[5,2];
    int [,] array3 = new int[6,4];


    // HERE the needed cast
    int[,] Myarray1 = (int[,])Myarraylist[1];

    for (int n = 0; n < 2; n++)
        Console.WriteLine("MyArray1[0,{0}]={1}", n, Myarray1[0, n]);

BTW as the following note (from MSDN[^]) says

Applications that target version 2.0 and later of the .NET Framework should use the generic collection classes in the System.Collections.Generic namespace, which provide greater type-safety and efficiency than their non-generic counterparts.

I strongly suggest you using generic containers instead of ArrayList.

Share this answer
CS2011 23-May-11 7:50am    
have 5+ for this. Good answer
CPallini 23-May-11 8:31am    
Thank you.
Kim Togo 23-May-11 7:59am    
Good answer, 5.
CPallini 23-May-11 8:31am    
Wonde Tadesse 23-May-11 8:06am    
Nice answer. 5 :)
Don't use the ArrayList; it was rendered obsolete when generics were introduced in v.2.0. Use System.Collections.Generic.List. In your case, use System.Collections.Generic.List<System.Collections.Generic.List<int>>.

It will represent jagged array. Use System.Collections.Generic.List.ToArray to get an array of rank 1. The element will be lists, use each one with ToArray to get nested array elements.

Share this answer
Al-Samman Mahmoud 24-May-11 8:54am    
thank u for ur help and i will use generic it seems to be more accurate and easier.
Sergey Alexandrovich Kryukov 24-May-11 12:47pm    
You're welcome.
If you think it's useful please formally accept this answer (you can accept more than 1).
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900