How to retrieve Object and its member from arraylist in c#.
6 Answers
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
Comments
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;
Comments
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.
1 Comment
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
Comments
Do a type casting like this:
yourObject = new object[]{"something",123,1.2};
((System.Collections.ArrayList)yourObject)[0];