I want to iterate through an ArrayList that I’ve added objects to.
// in Duck : Animal class
public Duck(string name, Gender gender, int age) : base(name, gender, age) { }
public static Duck duck1 = new Duck ("Dolly", Gender.Female, 8);
// in Animal class
private static ArrayList animalList = new ArrayList()
{
Duck.duck1
};
In console app I want to be able to do this:
public static void Main()
{
foreach (var item in AnimalList)
Console.WriteLine(item.Name);
}
// desired output:
Dolly
But since I added duck1, it prints the path " NewPondLibrary.Pond+Animal+Duck " I’m totally lost on how to achieve what I want, is adding objects to array like this just not possible? I added Duck.duck1 to the arraylist because I don’t know another way to add objects to an array WITH parameters from the constructor.
The tutorials I looked at only show arraylists that have just a string or int item and no other information. I’m also curious how arraylist can be useful if just one line of information is all you can add. I’m very new to C# so might be missing some key theory.
Would appreciate any help
>Solution :
Well, ArrayList
has items of type Object
that’s why this doesn’t compile
// Doesn't compile: item is of type Object, not Duck
foreach (var item in AnimalList)
Console.WriteLine(item.Name); // item is of type Object, not Duck
You can change ArrayList
into List<Duck>
:
private static List<Duck> animalList = new List<Duck>() {
Duck.duck1
};
If you insist on using obsolete ArrayList
you can filter Duck
s either with a help of Linq
using System.Linq;
...
foreach (var item in AnimalList.OfType<Duck>())
Console.WriteLine(item.Name); // item is of type Object
or without:
foreach (var item in AnimalList)
if (item is Duck duck)
Console.WriteLine(duck.Name);