Covariance can be extended to generic types and used with predefined delegates (remember, those delegates supplied by the Framework Factory that can be of types Action, Predicate, and Func).
To place a simple code that shows this feature, observe the following declaration:
IEnumerable<Func<Polygon>> dp =
new List<Func<Rectangle>>();
Here, we're assigning a list of delegates of type Rectangle to an enumerable of delegates of type Polygon. This is possible because three characteristics play their role:
Rectangle is assignable to Polygon for Substitution Principle
Func<Rectangle> is assignable to Func<Polygon> due to covariance in the generic out T parameter of Func<T>
Finally, IEnumerable<Func<Rectangle>> is assignable to IEnumerable<Func<Polygon>> due to a covariance extension over the generic type out T of IEnumerable
Consider this code, where we change the defined polygons identifier as type IEnumerable<Polygon>:
IEnumerable<Polygon> polygons2 =
new List<Triangle> {
new Triangle(), new Triangle()};
This doesn't lead to a compilation error because the same ideas are applied to interfaces. To allow this, the generic parameter of interfaces such as IEnumerable<T> is used only as an out value. In such cases, it's interesting to take a look at the definition using the Peek Definition option (available on the editor's context menu for any type):
The implementation of tuples in .NET 4 is based on the definition (mscorlib.dll assembly and the System namespace) of eight generic classes Tuple<> with different number of type parameters to represent tuples of different cardinalities (it's also called arity).
As a complement to this family of generic classes, eight overloads of the Create method in the Tuple class are provided, converting it into a factory of many possible variations of these types. In order to deliver resources for the creation of longer tuples, the eighth tuple in the list can also be a tuple itself, allowing it to grow as required.
The following code shows the implementation of one of these methods. Thus, to create tuples, we can take advantage of a more concise notation and write this: