Covariance & Contravariance enables implicit reference conversion of parameters for arrays, delegates & generic types.
These concepts introduced in .Net framework 4.0, before it was not works
Covariance: Covariance allows more derived return type method than delegate's return type to be assigned.These concepts introduced in .Net framework 4.0, before it was not works
Return type of method GetString is 'string' that is more derived type than return type of delegate Func that is 'object'.
1. Func<object> delFun = GetString; //See below code
2. IEnumerable<string> strs = new List<string>();
IEnumerable<object> objects = strs;
Contravariance: Contravariance allows less derived parameter types method than delegates parameters type to be assign.
Parameter of setobject method 'object' is less derived type than parameter of delegate Action that is 'string'.
Action<string> delAct = SetObject;
Examples
class Program
{
static void Main(string[] args)
{
//Covariance
Func<object> delFun = GetString;
//Contravariance
Action<string> delAct =
SetObject;
}
static string GetString()
{
return string.Empty;
}
static void SetObject(object obj)
{
}
}
No comments:
Post a Comment