Introduction
Covariance and Contravariance of generic
type parameters for interfaces and delegate types. covariance and
contravariance enable to use reference conversion, and do not support value
type. Covariance and contravariance bring flexibility to programming. Below
in the given example show covariance and contravariance in delegate.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Covariance_and_contravariance_in_c_sharp
{
class
Program
{
static
object Get_Object()
{
return
"return object";
}
static
void Set_Object(object
o)
{
}
static
string Get_String()
{
return
"Return String";
}
static
void Set_String(string
s)
{
}
static
void Main(string[]
args)
{
/* Covariance.
A delegate, which is return type as object,
but we can assign a method,
which returns a string.*/
Func<object>
dgate1 = Get_String;
/*
Contravariance. A delegate, which is a parameter type as
string,
but we can assign a method
that takes an object.*/
Action<string>
dgate2 = Set_Object;
Console.WriteLine(Get_String());
Console.WriteLine(Get_Object());
Console.ReadLine();
}
}
}
Output: