Click here to Skip to main content
15,850,360 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:

I have got a struct for ex:

struct MyObject
    Point Location; 
    Color c;

And I am using an ArrayList for keep them together ex:

ArrayList MyList = new ArrayList();
MyObject obj = new MyObject();
obj.Location = new Point(0, 0);
obj.c = Color.White;

The problem is

I want to use an object's properties from ArrayList with specified index like:


but I have to convert MyList[0] to MyObject first. Because It is an Object type thats why I cannot reach MyObject's properties.

How can I do that?


(Btw) I do not want to use normal arrays because I will be using Add and RemoveAt functions a lot.
Updated 16-Feb-11 8:39am

With classes like this you always will need type cast for collection's element.

In general case:
object whoKnowsWhat //...
MyObject my = whoKnowsWhat as MyObject;
if (my == nulll) //... do something like throwing exception or ignoring
my./... use my

//If you're already sure is of the right class
//(and not null, already cheched), type cast directly:
MyObject my = (MyObject)whoKnowsWhat;
//if it's wrong, not problem, the code above will throw exception,
//so you could recover

Don't do all that in your case!

Simply don't use name space System.Collections, it's mostly obsolete; use System.Collections.Generic instead. At least you will be away from the problems with casting.

Share this answer
Use a List<MyObject> instead. ArrayList is not going to let you do what you want to do.
Share this answer
Albin Abel 16-Feb-11 13:42pm    
both answers are same, 5 each
public struct MyObj
    public Point Location;
    public Color c;
public void test()
    List<MyObj> MyList = new List<MyObj>();
    MyObj[] abc = new MyObj[5];

    for (int i = 0; i < 5; i++)
        abc[i].Location = new Point();
        abc[i].c = new Color();

        //to add in the List

    //gets the number of items in the List
    int count = MyList.Count;

    //gets the capacity of List
    int cap = MyList.Capacity;

    //Removes All elements from the List

    //inser the object at the specified index in List
    MyList.Insert(2, abc[3]);

    //removes the object from specified index

    //Removes all elements from the List
Share this answer

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