Covariance – solve

  • Covariance is implemented with generics.
  • Out keyword has to be used
    • this will not work !!
      IPlay<Cricket> cricketer= new Play<ODICricket>();
    • public interface IPlay<out T>
      {
        T PlayCricket();
      }
				
					namespace Covariance
{
    public interface IPlay<out T>
    {
        T PlayCricket();
    }

    public class Play<T> : IPlay<T> 
    {
        public T obj { get; set; }  
        public T PlayCricket()
        {
            return obj;
        }
    }

    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 Covariance;
IPlay<Cricket> cricketer= new Play<ODICricket>() { obj=new ODICricket()};
var obj =cricketer.PlayCricket();
obj.Play();

				
			

ODICricket play

  • Interface<Parentclass> object= new ClassName<childClass>() ;
  • ClassName : Interface
  • use out keyword
  • Interface :- 
    • public interface IPlay<out T>
      {
      T PlayCricket();
      }

Leave a Comment