Child pages
  • Co-variant array conversion may cause exception on write operation

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Consider the following code listing

Code Block
csharp
csharp
class MyForm : Form
{
  ProcessFiles()
  {
    var ofd = new OpenFileDialog();
    ofd.ShowDialog();
    BeginInvoke(new Action<string[]>(Process), ofd.FileNames);
  }

  private void Process(string[] files)
  {
    // process each of the files
  }
}

This code shows an Open File Dialog and then attempts to asynchronously process the chosen files. However, what the developer has missed is that the BeginInvoke() method actually takes a params object[] argument, to which the developer is passing an array of strings. As a consequence, ReSharper offers a warning, saying that the covariant array conversion from string[] to object[] may cause an exception at run-time.

The issue with the above code is easily resolved: since BeginInvoke() expects to receive an array of all the parameters and there is only one parameter (string[] files), all we have to do is provide exactly that, i.e.,

Code Block
csharp
csharp
BeginInvoke(new Action<string[]>(Process), new object[]{ ofd.FileNames });