Search code examples
c#resharperstring-conversioncovariantcovariant-return-types

Why does Resharper say, "Co-variant array conversion from string[] to object[] can cause run-time exception on write operation" with this code?


This code:

comboBoxMonth.Items.AddRange(UsageRptConstsAndUtils.months.ToArray());

public static List<String> months = new List<String>
{
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
};

Turns R# curmudgeon-like with the complaint, "Co-variant array conversion from string[] to object[] can cause run-time exception on write operation".

Actually, this code works perfectly - the combo box is populated with the month values; what is Resharper on about, and what can I do to assuage its doubts?

If it's simply that the generic list may contain bad data, I won't worry about it - and if there ever were a problem, it would be easy enough to track down the problem.


Solution

  • The method comboBoxMonth.Items.AddRange expects an object[] parameter. months.ToArray() is string[]. A cast from string[] to object[] is valid, but if the method tries to modify elements of the array, you will get run-time errors. In this case it doesn't, so you can ignore the warning.

    If it annoys you, you can use ToArray<object>()

    comboBoxMonth.Items.AddRange(UsageRptConstsAndUtils.months.ToArray<object>());
    

    It will return object[] and no cast will be needed.