In C #, how can I create an IEnumerable <T> class with various types of objects>
3 answers
another approach if you need a named collection (instead of using a List<T> ):
// animal classes public class Animal { public String Name { get; set; } public Animal() : this("Unknown") {} public Animal(String name) { this.Name = name; } } public class Dog : Animal { public Dog() { this.Name = "Dog"; } } public class Cat : Animal { public Cat() { this.Name = "Cat"; } } // animal collection public class Animals : Collection<Animal> { } Implementation:
void Main() { // establish a list of animals and populate it Animals animals = new Animals(); animals.Add(new Animal()); animals.Add(new Dog()); animals.Add(new Cat()); animals.Add(new Animal("Cheetah")); // iterate over these animals foreach (var animal in animals) { Console.WriteLine(animal.Name); } } Here you set aside the foundation of Collection<T> , which implements IEnumerable<T> (so foreach and other iteration methods work with it).
+1
public class Animal { } public class Dog : Animal { } public class Cat : Animal { } List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); Then you can iterate over the collection with:
foreach (var animal in animals) { Console.WriteLine(animal.GetType()); } +14