8

How to retrieve Object and its member from arraylist in c#.

1
  • If you are used to Java you might wan't to know that ArrayList isn't the same as in Java. There are many other collection types in C# List<ObjectType> is typesafe for example. Commented Jul 29, 2010 at 15:45

6 Answers 6

19

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

Sign up to request clarification or add additional context in comments.

Comments

6
    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

Comments

2

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

2

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

This is c#. Not Java.
1

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

0

Do a type casting like this:

yourObject = new object[]{"something",123,1.2};

((System.Collections.ArrayList)yourObject)[0];

1 Comment

This is the opposite of what the question asks.

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.