Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert value type array to params object[]

Tags:

c#

.net

If C# can cast an int to an object, why not an int[] to an object[]?

Simple Program Example:

void Main()
{
    var a = new String[]{"0", "1"};
    var b = new int[]{0, 1};

    AssertMoreThan1(a); // No Exception
    AssertMoreThan1(b); // Exception
}

static void AssertMoreThan1(params object[] v){
    if(v.Length == 1){
        throw new Exception("Too Few Parameters");
    }
}
like image 853
Daryl Avatar asked Feb 01 '12 22:02

Daryl


2 Answers

If C# can cast an int to an object, why not an int[] to an object[]?

Your question could be also stated as "what are the covariance rules for array conversions in C#?"

They are a bit tricky, and broken in several interesting and unfortunate ways.

First off, we should clearly state what we mean by "covariance". Covariance is the property that a mapping preserves a relationship. The mapping here is "T goes to array of T". The relationship is "can be implicitly converted". For example:

Giraffe can be implicitly converted to Mammal.

That's a relationship between two types. Now apply the mapping to both sides of the relationship:

Giraffe[] can be converted to Mammal[].

If the truth of the first statement always entails the truth of the second statement -- that is, if the mapping preserves the truth of the relationship -- then the mapping is said to be "covariant".

As a shorthand, instead of saying "the mapping from T to array of T is a covariant mapping over the implicit conversion relation", we just say "arrays are covariant" and hope that the rest of that is understood from context.

OK, now that we have the definition down: Arrays with reference type elements are covariant in C#. Tragically, this is broken covariance:

class Mammal {}
class Giraffe : Mammal {}
class Tiger : Mammal {}
...
Mammal[] mammals = new Giraffe[1];  

This is perfectly legal because arrays of reference type elements are covariant in C#. But then this crashes at runtime:

mammals[0] = new Tiger();

because mammals is really an array of Giraffes.

This means that every time you write to an array whose elements are unsealed reference types, the runtime performs a type check and might crash if the type check fails.

This is my candidate for "worst feature of C#", but it does in fact work.

Your question is "why does array covariance not work when the source array is an array of value type and the target array is an array of reference type?"

Because those two things have a different form at runtime. Suppose you have a byte[] with ten elements. The actual storage reserved for the array elements is ten bytes long. Suppose you are on a 64 bit machine and you have an object[] with ten elements. The storage is eight times bigger!

Clearly you cannot convert via reference conversion a reference to storage for ten bytes to storage for ten eight-byte references to bytes. The extra seventy bytes don't come out of nowhere; someone has to allocate them.

Moreover: who does the boxing? If you have an array of ten objects and each object is a byte, each one of those bytes is boxed. But bytes in a byte array are not boxed. So when you do the conversion, who does the boxing?

In general in C#, covariant conversions always preserve representation. The representation of a "reference to Animal" is exactly the same as the representation of "reference to Giraffe". But the representations of "int" and "reference to object" are completely different.

One expects that casting one array type to another does not allocate and copy a huge array. But we cannot have referential identity between an array of ten bytes and an array of eighty bytes containing ten references, and therefore the entire thing is simply made illegal.

Now, you might then say, well, what happens when the representations are the same for value types? In fact, this is illegal in C#:

int[] x = new uint[10];

because in C# the rule is that only covariant array conversions involving only reference types are legal. But if you force it to be done by the runtime:

int[] x = (int[])(object) new uint[10];

Then the runtime allows it because a four byte int and a four byte uint have the same representation.

If you want to understand this better then you should probably read my entire series of articles on how covariance and contravariance works in C#:

  • The whole series

  • The specifics of unsafe reference-element array covariance

  • More about value-element array covariance

like image 174
Eric Lippert Avatar answered Nov 06 '22 17:11

Eric Lippert


Indeed, you cannot convert that. Reference-type arrays are covariant; value-type arrays are not. So; you will have to use one of:

an array of boxed values:

var b = new object[] {0,1};

or you could use IList:

static void AssertMoreThan1(IList v) {
   ... (check with .Count)
}

or generics:

static void AssertMoreThan1<T>(T[] v) {
   ...
}

The last one would be my preference.

like image 8
Marc Gravell Avatar answered Nov 06 '22 18:11

Marc Gravell