Alex Rivera | Logout

string.Format fails at runtime with array of integers

Asked 2010-07-15T17:24:19.440
22

Consider string.Format() whose parameters are a string and, among others in the overload list, an object[] or many objects.

This statement succeeds:

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

as does this:

object[] myObjs = new object[] {8,9};
string baz = string.Format("{0} and {1}", myObjs;

as does an array of strings:

string[] myStrings = new string[] {"abc", "xyz"};
string baz = string.Format("{0} {1}", myStrings);

It seems that the integers, when specified individually, can be boxed or coerced to type object, which in turn is coerced to a string.

This statement fails at runtime.

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

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

  • Why doesn't or can't the int array be coerced or boxed to an object[] or string[]?
  • Out of a small bit of curiosity, why doesn't the compiler catch this?
Edit
Report

1 Answer

3

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

answered 2010-07-15T17:34:31.037

Your Answer