Code inspection: Co-variant array conversion
Category: Potential Code Quality Issues
ID: CoVariantArrayConversion
EditorConfig: resharper_co_variant_array_conversion_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
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 runtime 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 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.