0

I found this code to generate a two dimensional Dynamic Array with different types but how can i access for example: ar[0]->o[0] ?

Thx!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;

namespace Collections
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList ar = new ArrayList();
            object[] o = new object[3];
            // Add 10 items to arraylist
            for (int i = 0; i < 10; i++)
            {
                // Create some sample data to add to array of objects of different types.
                Random r = new Random();
                o[0] = r.Next(1, 100);
                o[1] = "a" + r.Next(1,100).ToString();
                o[2] = r.Next(1,100);
                ar.Add(o);
            }
        }
    }
}
1
  • Why do you even want this code that you found? Commented Jun 25, 2013 at 11:13

1 Answer 1

3

You can use it like this:

((object[])ar[1])[2]

to obtain the third object in the second array, but be aware that you must cast this to the proper type since you are using an object array.

I would instead rather recommend this approach, create your own class that will hold your data. That way you won't need to take care of casting the object to proper types.

public class Randoms
{
     public int Rand1 { get; set; }
     public string Rand2 { get; set; }
     public int Rand3 { get; set; }
}

and then use the Generic List

List<Randoms> = new List<Randoms>();

So at the end the code would look like this:

List<Randoms> ar = new List<Randoms>();
// Add 10 items to list
for (int i = 0; i < 10; i++)
{
       Randoms rand = new Randoms();
       Random r = new Random();
       rand.Rand1 = r.Next(1, 100);
       rand.Rand2 = "a" + r.Next(1, 100).ToString();
       rand.Rand3 = r.Next(1, 100);
       ar.Add(rand);
}
Sign up to request clarification or add additional context in comments.

Comments

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.