CSharp - Covariance with Generic Interfaces

Description

Covariance with Generic Interfaces

Demo

using System;
using System.Collections.Generic;

class Parent/*  w  ww .  j av a2s  .c  o  m*/
{
    public virtual void ShowMe()
    {
        Console.WriteLine(" I am from Parent, my hash code is :" + GetHashCode());
    }
}
class Child : Parent
{
    public override void ShowMe()
    {
        Console.WriteLine(" I am from Child, my hash code is:" + GetHashCode());
    }
}
class Program
{
    static void Main(string[] args)
    {

        Parent pob1 = new Parent();
        Parent pob2 = new Parent();
        //Some Child objects
        Child cob1 = new Child();
        Child cob2 = new Child();
        //Creating a child List
        List<Child> childList = new List<Child>();
        childList.Add(cob1);
        childList.Add(cob2);
        IEnumerable<Child> childEnumerable = childList;

        IEnumerable<Parent> parentEnumerable = childEnumerable;
        foreach (Parent p in parentEnumerable)
        {
            p.ShowMe();
        }
    }
}

Result

Related Topic