Co-variant array conversion from x to y may cause run-time exception

TheVillageIdiot picture TheVillageIdiot · Jan 2, 2012 · Viewed 32.9k times · Source

I have a private readonly list of LinkLabels (IList<LinkLabel>). I later add LinkLabels to this list and add those labels to a FlowLayoutPanel like follows:

foreach(var s in strings)
{
    _list.Add(new LinkLabel{Text=s});
}

flPanel.Controls.AddRange(_list.ToArray());

Resharper shows me a warning: Co-variant array conversion from LinkLabel[] to Control[] can cause run-time exception on write operation.

Please help me to figure out:

  1. What does this means?
  2. This is a user control and will not be accessed by multiple objects to setup labels, so keeping code as such will not affect it.

Answer

Anthony Pegram picture Anthony Pegram · Jan 2, 2012

What it means is this

Control[] controls = new LinkLabel[10]; // compile time legal
controls[0] = new TextBox(); // compile time legal, runtime exception

And in more general terms

string[] array = new string[10];
object[] objs = array; // legal at compile time
objs[0] = new Foo(); // again legal, with runtime exception

In C#, you are allowed to reference an array of objects (in your case, LinkLabels) as an array of a base type (in this case, as an array of Controls). It is also compile time legal to assign another object that is a Control to the array. The problem is that the array is not actually an array of Controls. At runtime, it is still an array of LinkLabels. As such, the assignment, or write, will throw an exception.