Reputation: 3171
In C# how can I create an IEnumerable<T>
class with different types of objects
For example:
Public class Animals
{
Public class dog{}
Public class cat{}
Public class sheep{}
}
I want to do some thing like:
Foreach(var animal in Animals)
{
Print animal.nameType
}
Upvotes: 6
Views: 857
Reputation: 101614
another approach if you wanted a named collection (instead of using a 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 extend off the foundation of Collection<T>
which implements IEnumerable<T>
(so foreach
and other iterating methods work from it).
Upvotes: 1
Reputation: 6801
Create an Animal base class. Let each specific animal inherit from Animal. Create an abstract method in Animal called NameType, that each subclass overrides. Create a List<Animal>
and iterate over that.
Upvotes: 1
Reputation: 70748
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());
You can then iterate over the collection via:
foreach (var animal in animals) {
Console.WriteLine(animal.GetType());
}
Upvotes: 15