ReSharper 2016.3 Help

Code Inspection: Co-variant array conversion

C# allows you to reference an array of derived types as an array of base types. As explained in this Eric Lippert's post, this design has its benefits and its problems. Speaking about problems, let's take a look at the example below. When we pass string[] myStrings to the ChangeFirstItem(object[] myArray), we still have an array of strings, not objects. Therefore, when we try to assign an int value to the first array element, we get ArrayTypeMismatchException at runtime. ReSharper detects the problem here and issues a warning.

void Test() { string[] myStrings = { "one","two","three" }; ChangeFirstItem(myStrings); //Co-variant array conversion can cause run-time exception... Console.WriteLine(myStrings[0]); } void ChangeFirstItem(object[] myArray) { myArray[0] = 10; //ArrayTypeMismatchException at runtime }

There are several ways to fix issues of this kind. ReSharper suggests you quick-fixes that either change the type of the initial array to the array of base types, or change the type of the accepting parameter to the array of derived types.

Along with these two fixes, you can also make use of the ToArray<T>() method, i.e: myStrings.ToArray<object>(). Note that this fix will not work in the above example as ToArray<T>() will create a copy of the array.

See Also

Last modified: 3 April 2017