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.
There are several ways to fix issues of this kind. ReSharper suggests 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.