How do you cast a dictionary<int, child> to dictionary<int, parent>?

Maybe something like this?

void IterateTable<T>(Dictionary<int, T> dictionary)
    where T : Animal
{
    foreach(var entry in dictionary)
        entry.Value.Attack();
}

Your code works as written. When the Animal in the dictionary's value has its Attack() method called, it invokes the appropriate, animal-specific method. This is called covariance. You can provide a more specific type to the dictionary than required by its signature.

You can modify your code as follows to see:

void Main()
{
    Dictionary<int, Animal> dictionary = new Dictionary<int, Animal>()
    {
        [1] = new Lion(),
        [2] = new Boar()
    };

    IterateTable(dictionary);
}

public class Animal
{
    virtual public void Attack() { Console.WriteLine("Default animal attack"); }
}
public class Lion : Animal
{
    public override void Attack() { Console.WriteLine("Lion attack"); }
}
public class Boar : Animal
{
    public override void Attack() { Console.WriteLine("Boar attack"); }
}

void IterateTable(Dictionary<int, Animal> dictionary)
{
    foreach (var entry in dictionary)
        entry.Value.Attack();
}

Output:

Lion attack

Boar attack

Tags:

C#