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
}
The ' |= ' symbol is the bitwise OR assignment operator.
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 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());
You can then iterate over the collection via:
foreach (var animal in animals) {
Console.WriteLine(animal.GetType());
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With