ReSharper 2016.1 Help

Code Inspection: Co-variant array conversion

Consider the following code listing:

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.,

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

See Also

Last modified: 19 August 2016