Reputation: 1020
How to retrieve Object and its member from arraylist in c#.
Upvotes: 8
Views: 58540
Reputation: 44275
object[] anArray = arrayListObject.ToArray();
for(int i = 0; i < anArray.Length; i++)
Console.WriteLine(((MyType)anArray[i]).PropertyName); // cast type MyType onto object instance, then retrieve attribute
Upvotes: 6
Reputation: 74
Do a type casting like this:
yourObject = new object[]{"something",123,1.2};
((System.Collections.ArrayList)yourObject)[0];
Upvotes: 0
Reputation: 56
You should use generic collections for this. Use the generic ArrayList so you dont have to cast the object when you are trying to get it out of the array.
Upvotes: 2
Reputation: 4749
You can also use extension methods:
ArrayList list = new ArrayList();
// If all objects in the list are of the same type
IEnumerable<MyObject> myenumerator = list.Cast<MyObject>();
// Only get objects of a certain type, ignoring others
IEnumerable<MyObject> myenumerator = list.OfType<MyObject>();
Or if you're not using a newer version of .Net, check the object type and cast using is/as
list[0] is MyObject; // returns true if it's an MyObject
list[0] as MyObject; // returns the MyObject if it's a MyObject, or null if it's something else
Edit: But if you're using a newer version of .Net...
I strongly suggest you use the Generic collections in System.Collections.Generic
var list = new List<MyObject>(); // The list is constructed to work on types of MyObject
MyObject obj = list[0];
list.Add(new AnotherObject()); // Compilation fail; AnotherObject is not MyObject
Upvotes: 1
Reputation: 9361
Here's an example of a simple ArrayList being populated with a new KeyValuePair object. I then pull the object back out of the ArrayList, cast it back to its original type and access it property.
var testObject = new KeyValuePair<string, string>("test", "property");
var list = new ArrayList();
list.Add(testObject);
var fetch = (KeyValuePair<string, string>)list[0];
var endValue = fetch.Value;
Upvotes: 2
Reputation: 115488
You mean like this?
ArrayList list = new ArrayList();
YourObject myObject = new YourObject();
list.Add(myObject);
YourObject obj = (YourObject)list[0];
To loop through:
foreach(object o in list)
{
YourObject myObject = (YourObject)o;
.......
}
Information on ArrayList
Upvotes: 19