Covariance and contravariance in C# 4.0


C# 4.0 introduces covariance and contravariance (together variance) for generic type parameters. These two concepts are similar and allow the use of derived or base classes in a class hierarchy.

An easy way to understand the difference between the two concepts is to consider the activity of the user of the variables passed to / from the generic method (interface or delegate.)

Contravariance

If the method implementation is only using variables passed with the parameter for read activity – then the generic parameter is a candidate for contravariance. The ‘read only’ role of the parameter type can be formalised by marking it with the in keyword – i.e. it is an input to the implementation.

Any generic type parameter marked with the in keyword will be able to match to types that are derived from the named type. In this case the implementation is the user of the variables. It makes sense to allow derived classes as any read activities that are available on the base class will also be available on any derived class.

// C# 3.0 does not recognise the in keyword for parameterized types
public delegate void TypeReporter<in T>(T input);

public void DoSomeGenericContravariance(RoutedEventArgs args)
{
    TypeReporter<EventArgs> ReportMethod
                  = new TypeReporter<EventArgs>(this.SimpleReportMethod);

    // C# 3.0 and earlier will not compile the following
    TypeReporter<RoutedEventArgs> RoutedReportMethod = ReportMethod;

    RoutedReportMethod(args);
}

public void SimpleReportMethod(EventArgs args)
{
    Console.WriteLine(args.GetType().ToString());
}

Covariance

Similarly – if a method implementation is only using variables passed with the parameter for write activity – then the generic parameter is a candidate for covariance. The ‘write only’ role of the parameter type can be formalised by marking it with the out keyword – i.e. it is an output from the implementation.

Any generic type parameter marked with the out keyword will be able to match to types that are base classes of the named type. In this case the calling / client code can be considered the user of the variables – so again it makes sense. Any operation (read or write) that is available on the base class that the client code has requested will also be available on the actual (derived) type that the implementation instantiates / sends as output.

public void DoSomeGenericCovariance()
{
    // The generic IEnumerable interface is defined with the out keyword
    // on the parameter type:
    //
    // public interface IEnumerable<out T> : IEnumerable

    List<String> strings = new List<String> { "one", "two" };
    IEnumerable<String> myStrings = strings.AsEnumerable();

    // C#3.0 and earlier will not compile the following
    IEnumerable<object> myObjects = myStrings;

    foreach (object myObject in myObjects)
    {
        Console.WriteLine(myObject.ToString());
    }
}

Issues to consider

Once type parameters have been marked with the in or out keyword the compiler will validate the interface / delegate compliance with the assigned variance. E.g. if the first example is changed to return the parameter passed, then the compiler will report an error – as the parameter is not being used for input only.

// Compiler will report a variance validation error
public delegate T TypeReporter<in T>(T input);

Variance uses reference type conversion – so it will not work with value types. Even though within the type system int inherits from object, the following will not compile.

List<int> ints = new List<int> { 1, 2 };
IEnumerable<int> myInts = ints.AsEnumerable();

// Reference type conversion not available
IEnumerable<object> myIntObjects = myInts;
Advertisement

Optional parameters and named parameters in C#4.0


If you are familiar with C++ or VB then you will already be familiar with optional parameters. They are parameters that are assigned a default value at compile time and that can be omitted when calling a method.

  public void LayoutElements(IList<Element> elements, int xOrig = 0, int yOrig = 0)
  {
    ...
  }
  
    ...

    layoutTool.LayoutElements(elementList);         // Will layout at 0, 0
    layoutTool.LayoutElements(elementList, 25, 25)  // Will layout at 25, 25

C#4.0 adds the ability to define optional parameters for methods, constructors and indexers.

An obvious area of use is constructors. Optional parameters remove the need to define multiple overloaded constructors with a variety of parameters all calling into a single constructor which does the work.

Any optional parameters must be declared after all non-optional parameters. You can overload a method to have two versions – one with an optional parameter and one without. In this case the compiler will resolve to the method without the optional parameter (following the principal of least surprise.)

    
  public void LayoutElements(IList<Element> elements)
  {
     LayoutElements(elements, 5, 5);
     ...
  }

  public void LayoutElements(IList<Element> elements, int xOrig = 0, int yOrig = 0)
  {
    ...
  }

    ...

    // Resolves to first method - will layout at 5, 5
    layoutTool.LayoutElements(elementList);

Another addition, named parameters, helps when calling a method, constructor or indexer. Similar in function to named parameters used with attributes.

You use the name of the variable to fill the parameter – using a colon to specify the value.

  // Will layout at 0, 10
  layoutTool.LayoutElements(elementList, yOrig: 10);

Named parameters can be used for both optional and positional parameters. When making the function call all named parameters must occur after any positional parameters. The named parameters do not have to appear in the order of the parameters in the method declaration.

  // Will layout at 15, 10
  layoutTool.LayoutElements(yOrig: 10, xOrig: 15, elements: elementList);

If you use partial methods, then for both optional and named parameters the declaration in the definition is used at compile time.

  partial void LayoutElements(IList<Element> elements, int xOrig = 0, int yOrig = 0);

   ...

  partial void LayoutElements(IList<Element> elements, int x = 5, int y = 5)
  {
    ...
  }

    ...

//    layoutTool.LayoutElements(elementList, y : 10);    // Will not compile
    layoutTool.LayoutElements(elementList, yOrig : 10);  // Will layout at 0, 10

Be aware that if you rename parameters in a method that is called elsewhere with the named parameter syntax, then the names will no longer match and the calling code will not compile.