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

I have got a struct for ex:

C#
struct MyObject
{
    Point Location; 
    Color c;
}


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

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


The problem is

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

C#
MyList[0].Location


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?


Thanks.

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

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

In general case:
C#
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.

—SA
 
Share this answer
 
v2
Use a List<MyObject> instead. ArrayList is not going to let you do what you want to do.
 
Share this answer
 
Comments
Albin Abel 16-Feb-11 13:42pm    
both answers are same, 5 each
C#
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
        MyList.Add(abc[i]);
    }

    //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
    MyList.Clear();

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

    //removes the object from specified index
    MyList.RemoveAt(2);

    //Removes all elements from the List
    MyList.Clear();
}
 
Share this answer
 
v2

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