Search code examples
c#arraysstring-formatting

string.Format fails at runtime with array of integers


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?

Solution

  • 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[].