KEY POINTS
- 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();
}
- this will not work !!
namespace Covariance
{
public interface IPlay
{
T PlayCricket();
}
public class Play : IPlay
{
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");
}
}
}
PROGRAM.CS
using Covariance;
IPlay cricketer= new Play() { obj=new ODICricket()};
var obj =cricketer.PlayCricket();
obj.Play();
OUTPUT
ODICricket play
Final Take
- Interface<Parentclass> object= new ClassName<childClass>() ;
- ClassName : Interface
- use out keyword
- Interface :-
- public interface IPlay<out T>
{
T PlayCricket();
}
- public interface IPlay<out T>