lickashot123

I created my own class and then created several instances of this class and added them to an ArrayList.



[code]

ArrayList me = new ArrayList();
a b = new a();
me.add(a);

class a
{
int i;
string a;
string geta()
{
return a;
}
}
[/code]

How can I then return a single element from the arraylist so that I can then call the method geta() on that single element

The Java equivalent would be a.get(i).geta();

Thanks




Re: .NET Base Class Library Returning a single element from an ArrayList

ARK88

One option is this:

Code Snippet

((a)me[0]).geta();

Because an ArrayList contains System.Object, you need to cast the array element to your class before you can reference the method (as shown above).

Another (maybe a little better option) would be to use List<> instead of ArrayList...

Code Snippet

List<a> me = new List<a>();

me.Add( new a() );

me[0].geta();

The code above indicates the list contains items of class "a", therefore you don't need to cast them.