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
Arrays of reference-types are covariant, meaning: a
string[]can be treated as anobject[](although the gotcha is that if you try to put a non-string in, it willthrow). However, arrays of value-types are not covariant, so anint[]cannot be treated as anobject[].new[] {1,2}is anint[].IIRC this was done mainly for similarity with java. The covariance in .NET 4.0 is much tidier.