Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how can I create an IEnumerable<T> class with different types of objects>

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
}
like image 300
Milligran Avatar asked Jul 23 '13 15:07

Milligran


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

What is '~' in C programming?

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 ...

What is & operator in C?

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.


2 Answers

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());
}
like image 57
Darren Avatar answered Oct 07 '22 17:10

Darren


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).

like image 26
Brad Christie Avatar answered Oct 07 '22 15:10

Brad Christie