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;
Advertisements

C# and NUnit – testing interface implementations


A common development strategy is to generate interface definitions and then code against these – allowing the implementations to be varied easily.

When writing NUnit test cases for interfaces and implementing classes – it is possible to generate a set of test cases for the interface and then apply these test cases to each concrete implementation. A strategy is outlined below.

Within the class library containing the test cases generate a test fixture for the interface itself. A class member, m_fileManager in this case, is used to hold the interface instance to test and a second member m_runTests is used to track whether the fixture holds an interface realisation.

A virtual function CreateConcrete is defined to create the concrete interface implementation – it is called in the SetUp method.

Add the interface test cases to this class – checking whether tests should by run using the m_runTests member.

[TestFixture]
public class Test_IFileManager
{

    /// Interface to use for testing
    protected IFileManager m_fileManager;

    /// Indicator that we are in a realisation test fixture
    protected bool m_runTests = false;

    /// Create a concrete instance
    virtual public void CreateConcrete()
    {
    }
        
    [SetUp]
    /// Test set up
    public void Setup()
    {
        CreateConcrete();
    }

    [TearDown]
    /// Test tear down
    public void TearDown()
    {
        m_fileManager = null;
        m_runTests = false;
    }

    [Test]
    /// A simple test
    public void NonExistentDirectoryThrowsException()
    {
        if (m_runTests)
        {
            Console.WriteLine("Running test: NonExistentDirectoryThrowsException");

            Assert.Throws<DirectoryNotFoundException>
                ( delegate
                  {
                    m_fileManager.GetFreeFileName(@"ZZ:\BadDrive\", "stem", "txt");
                  });
        }
    }
}

To attach the set of test cases to a concrete implementation, generate a class that inherits this base interface testing class. Override the CreateConcrete method to assign the interface instance and to indicate that the tests should be run.

[TestFixture]
public class Test_IFileManager_SimpleFileManager : Test_IFileManager
{

    /// Create a concrete instance
    override public void CreateConcrete()
    {
        // Using static method
        m_fileManager = (IFileManager) SimpleFileManager.GetFileManager();
        m_runTests = true;
    }

}

Each implementing class can be tested by creating a separate concrete implementation testing class. When NUnit runs it finds all of the interface tests and runs them for each concrete implementation.

If any implementation-specific test cases exist, then they can be added to the concrete testing class. If a class implements multiple interfaces, then each interface can be tested in a similar manner by generating a concrete implementation testing class for each interface / implementer pair.

Software companies listed in the UK


With the news that Apple (AAPL) has overtaken Microsoft (MSFT) to become the largest software company in the world by market capitalisation it seems like a good time to have a look at the software companies listed in the UK.

Below are the details for the largest UK pure-play (almost) software companies. Limited to FTSE 350 components the sector has it’s own tracking index NMX9530.L

With a combined market capitalisation of approximately £18.3 b ($26.7 b) the whole sector is dwarfed by Apple at $231 b.

£4.18 b – Autonomy (AU.L) http://www.autonomy.com/
£3.11 b – Sage Group (SGE.L) http://www.sage.com/
£2.25 b – Invensys (ISYS.L) http://www.invensys.com/
£2.01 b – Logica (LOG.L) http://www.logica.com/
£1.69 b – Dimension Data (DDT.L) http://www.dimensiondata.com/
£1.22 b – Misys (MSY.L) http://www.misys.co.uk/
£987 m – Micro Focus (MCRO.L) http://www.microfocus.com/
£781 m – Aveva (AVV.L) http://www.aveva.com/
£753 m – Telecity Group (TCY.L) http://www.telecitygroup.com/
£488 m – Computacenter (CCC.L) http://www.computacenter.com/
£483 m – Fidessa Group (FDSA.L) http://www.fidessa.com/
£358 m – SDL (SDL.L) http://www.sdl.com/

Prices at close of 27 May 2010 from Yahoo Finance (http://uk.finance.yahoo.com/)

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.

Update UI from background worker thread without explicit marshalling


It is possible to update the UI thread from a background worker thread without the need to explicitly marshal the call across to the UI thread. An example follows.

A separate blog entry details how to update a UI using explicit marshalling.

The background worker member is used to perform potentially long lasting non-UI activities:

    private BackgroundWorker m_bw = new BackgroundWorker();

When starting the background worker (e.g. in the instance constructor after InitializeComponents for a WPF application) set the flag to indicate that the worker reports progress and add a ProgressChangedEventHandler:

    m_bw.DoWork += bw_DoWork;
    m_bw.WorkerReportsProgress = true;
    m_bw.ProgressChanged += bw_ProgressChanged;
    m_bw.RunWorkerAsync();

In the background worker activity when you want to update the UI call the ProgressChanged method on the background worker using the overload to pass a state object:

    int progress = 50;
    var state = new KeyValuePair<string, string>("Status", "Still working");
    m_bw.ReportProgress(progress, state);

The event that this call raises is raised on the thread that created the background worker – so in this case the UI thread – which means that implicit marshalling has occurred. In the ReportProgressEventHandler you can then directly update the UI controls:

    void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ...

        var state = (KeyValuePair<string, string>) e.UserState;
        m_xamlProgress.Text = e.ProgressPercentage + "%";
        m_xamlStatus.Text = "Status: " + state.Value;

        ...
    }

This approach separates the creation of the update data from the activity of updating the controls – providing an implicit interface between the worker thread and the UI thread.

In more complex scenarios where threads that have not been created by the UI thread need to update controls the mechanism of Control.InvokeRequired followed by use of Invoke / Dispatcher can be used.

Software expansion


I have often thought that identifying and exploring a new idea within software is like discovering a new bubble of understanding.  The rush of first identification of the idea is followed by a phase of exploration of the extent and internal structure of the idea – the expansion phase.  It does not matter if the idea has been had by someone before – if it is your first encounter with the idea, then it is all new.  It is all good.

After a while you may start to consider the value and facility of the idea and the means by which you would go about implementing it.  Implementation needs impose a framework that  does not necessarily represent the natural structure of the idea, but defines how it would be possible to engineer the idea using the tools that you know.

To me this highlights one of the great benefits of managed software environments like .Net and Java.  The richness of the framework and the wide availability of tools and libraries enable you to focus on the idea at hand, rather than preliminary work building a supporting infrastructure.

Once the software idea has been implemented, it is often difficult to communicate the newness of the idea to new developers joining the project.  This may be due to the fact that the idea is communicated in terms of the implementation frameworks that have been imposed on the idea – which are just projections of the idea onto known tools, techniques and choices.

Spring clean your usings


If you have worked on software that has been extended, upgraded and re-factored over time – then you will be aware that using statements accumulate at the top of C# files.  Some of these will be for namespaces and types that are no longer used in the code below.

An addition to the Visual Studio 2008 IDE is the ability to clean up and organise these using statements.

Just right-click to get the context menu in your code files and you will see the new menu option “Organize Usings”.  With this you can remove usings that are no longer in use, or sort the usings for a more aesthetic list.  Or why not go for a full clean up and do both!