Covariance With Interface C# with Example



Covariance With Interface C# with Example

 using System;

namespace CSharpGenerics
{
	public class BaseClass
	{
		public void Display()
		{
			Console.WriteLine("Base Class Method");
		}
	}
	public class DerivedClass : BaseClass {}
	
    public interface MyInterface		//Covariance
	{
		void Display();
	}

    class GenClass : MyInterface
    {
        public void Display()
        {
            Console.WriteLine("BaseClass Display Method.");
        }
    }

    class Program
    {
	    static void Action(MyInterface interfaceRef)	//Contravariance
        {
            interfaceRef.Display();
        }
		
        static void Main(string[] args)
        {
			GenClass derivedObject = new GenClass();
			MyInterface baseClassInterface = derivedObject;
			
			Action(baseClassInterface);
			//Action(derivedObject);
			
        }
    }
}
 

0 Comment's

Comment Form