Contravariance – intro

				
					namespace Contravariance
{
    public interface IPlay< in T>
    {
         void PlayCricket(T x);
    }

    public class Play<T> : IPlay<T> 
    {
        public void PlayCricket(T x)
        {
            if(x is ODICricket) 
             (x as ODICricket).Play();
            if (x is T20Cricket)
             (x as T20Cricket).Play();

        }
    }

    public class Cricket
    {
        public virtual void Play()
        {
            Console.WriteLine("cricket play");
        }
    }

    public class ODICricket : Cricket
    {
        public override void Play()
        {
            Console.WriteLine("ODICricket play");
        }
    }

    public class T20Cricket : Cricket
    {
        public override void Play()
        {
            Console.WriteLine("T20Cricket play");
        }
    }
}

				
			
				
					
using Contravariance;
IPlay<T20Cricket> cricketer1= new Play<Cricket>();
cricketer1.PlayCricket(new T20Cricket());

IPlay<ODICricket> cricketer2 = new Play<Cricket>();
cricketer2.PlayCricket(new ODICricket());

				
			

T20Cricket play
ODICricket play

  • public interface IPlay< in T>
  • Interface<childClass> obj= new ClassName<ParentClass>();
  • className implements interface

Leave a Comment