C# language feature:
applies to
benefit
how to use
out
modifier preceding type for co-variance, use in
modifier for contra-variance.see also
example:
class Base { }
class Derived : Base { }
class gernericvariance
{
delegate T Func<out T>();
delegate void Action<in T>(T a);
static void variance(string[] args)
{
// Covariance
Func<Derived> Derived = () => new Derived(); // Declare a delegate with return type defined as derived type (specified generic value)
Func<Base> Base = Derived; // Declare a delegate with return type defined base type and assign the derived delegate
// (which can be substituted where base is used, i.e. this is generic Covariance)
// Contravariance
Action<Base> basedel = (baseobj) => { Console.WriteLine(baseobj); }; // Declare a delegate with defined base type as parameter (specified generic value)
Action<Derived> derivedel = basedel; // Declare a delegate with defined derived type as parameter and assign the
// base delegate (when delegate is called with derived parameter object,
// this object can be substituted where base is expected.) This is generic Contravariance!
}
}