string.Format fails at runtime with array of integers

The call fails with the same reason the following will also fail:

string foo = string.Format("{0} {1}", 5);

You are specifying two arguments in the format but only specifying one object.

The compiler does not catch it because int[] is passed as an object which is a perfectly valid argument for the function.

Also note that array covariance does not work with value types so you cannot do:

object[] myInts = new int[] {8,9};

However you can get away with:

object[] myInts = new string[] { "8", "9" };
string bar = string.Format("{0} {1}", myInts);

which would work because you would be using the String.Format overload that accepts an object[].


I think the concept you are having an issue with is why int[] isn't cast to object[]. Here's an example that shows why that would be bad

int[] myInts = new int[]{8,9};
object[] myObjs = (object[])myInts;
myObjs[0] = new object();

The problem is that we just added an object into a int array.

So what happens in your code is that myInts is cast to object and you don't have a second argument to fill in the {1}


Your call gets translated into this:

string foo = string.Format("{0} {1}", myInts.ToString());

which results in this string:

string foo = "System.Int32[] {1}";

So as the {1} doesn't have a parameter, it throws an exception