ReferenceType and ValueType arrays are invalid object array argument

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 int array (ValueType), it doesn't work:

GetValueOrDefault(new[] {1, 2}, 0);

      

Compiler error:

Best overloaded method match for MyNamespace.GetValueOrDefault (object [], int) 'has some invalid Arguments

So my question is, why doesn't this compile as reference types and value type derived from an 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)
{...}

      

Thank you in advance

+3


source to share


1 answer


Arrays of reference types are covariant, which means: a string[]

can be treated like object[]

(although a gotcha is that if you try to put a nonlinear string it will throw

). However, arrays of value types are not covariant, so int[]

they cannot be thought of as object[]

. new[] {1,2}

is int[]

.



IIRC this was done mainly to be similar to java. Covariance in .NET 4.0 is much more complex.

+6


source







All Articles