I have a private readonly
list of LinkLabel
s (IList<LinkLabel>
). I later add LinkLabel
s 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:
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.