Iterating through List<interface> Items

I cant figure out why I cant iterate through a list by the class I have interfaced.

eg.

public interface IAnimal
{
   string Name { get; set; }
}

public class Chicken:IAnimal
{
   public string Name { get; set; }
}

public class Dog:IAnimal
{
   public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var AnimalList = new List<IAnimal>();

        var Chicken1= new Chicken() { Name = "Chicken" }; 
        var Dog1= new Dog() { Name = "Dog" };

        AnimalList.Add(Dog1);
        AnimalList.Add(Chicken1);

        foreach (Dog obj in AnimalList)
        {
           Console.WriteLine(obj.Name); 
        }
    }
}

Am i doing something wrong, is there a better angle to approach this sort of scenario.

Answers


You have defined your list so that it contains elements of IAnimal.

var AnimalList = new List<IAnimal>();

Then in your loop you're specifying the element as Dog. Now while Dog does implement IAnimal it's not the only type that does. So if the list contains a type other than Dog then your loop fails.

So you have two approaches to fix this.

One is you change your loop to be like this:

foreach (IAnimal obj in AnimalList)
{
    Console.WriteLine(obj.Name); 
}

If you do that your code works fine and outputs the name of the dog and chicken.

However, if you only wish to return the Dog instances you can filter the list. You'd do that like this:

foreach (Dog obj in AnimalList.OfType<Dog>())
{
    Console.WriteLine(obj.Name); 
}

Now it only results in outputting the dog name.


Each Dog is an IAnimal, but not each IAnimal is a Dog. Especially not Chicken: it's definitely not a Dog. That is why this loop is going to run into an exception when it reaches Chicken:

foreach (Dog obj in AnimalList) {
    ...
}

However, if you do it like this

foreach (IAnimal obj in AnimalList) {
    ...
}

or an equivalent

foreach (var obj in AnimalList) {
    ...
}

the code is going to compile and run correctly.


Need Your Help

How to highlight matching sub-strings inside a ListBox?

wpf listbox

I have one TextBox and one listbox for searching a collection of data. While searching a text inside a Listbox if that matching string is found anywhere in the list it should show in Green color with

Line Plus Bar with Multi Bars?

d3.js nvd3.js

I'm trying to make an chart using the default line plus bar chart, but I want to use two or more streams in the bars, is it possible?