Arrays of ReferenceType and ValueType are invalid argument of an object array
arrays, c#
Solution
Arrays of reference-types are covariant, meaning: a `string[]` can be treated as an `object[]` (although the gotcha is that if you try to put a non-string in, it will `throw`). However, arrays of value-types are not covariant, so an `int[]` cannot be treated as an `object[]`. `new[] {1,2}` is an `int[]`.
IIRC this was done mainly for similarity with java. The covariance in .NET 4.0 is much tidier.
Problem
I need to call the following function : ``` static string GetValueOrDefault(object[] values, int index) { if (values == null) return string.Empty; if (index >= values.Length) return string.Empty; return values[index] != null ? values[index].ToString() : string.Empty; } ``` When I call GetValueOrDefault with an array of strings (ReferenceType), it works : ``` GetValueOrDefault(new[] {"foo", "bar"}, 0); ``` When I call GetValueOrDefault with an array of int (ValueType), it doesn't work : ``` GetValueOrDefault(new[] {1, 2}, 0); ``` The compiler error is : The best overloaded method match for MyNamespace.GetValueOrDefault(object[], int)' has some invalid arguments So my question is : Why this doesn't compile as reference types and value type derive from object ? I know I can solve this problem using generics, but I want to understand this error ``` static string GetValueOrDefault<T>(T[] values, int index) {...} ``` Thanks in advance