Trouble using String.Format() with a DateTime array

I would appreciate help in understanding why the following C# code does not work.

//string[] array = new string[] { "a", "b", "c", "d" }; // this array works
var array = new [] {
       new DateTime(2000, 1, 1),
       new DateTime(2010, 12, 31)
};

var format = "{0:MMM}{1:MMM}";

Console.WriteLine(string.Format(format, array)); // compiles, but crashes at runtime

It compiles without issue, but crashes with the following error upon execution:

Run-time exception (line 15): Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Stack Trace: [System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.] at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.Format(String format, Object arg0) at Program.Main() :line 15

I expected that the String.Format overload that accepts an object array would work with the DateTime array just as it works with the string array, but am I misunderstanding something?

2 answers

  • answered 2020-03-31 09:33 Marc Gravell

    A DateTime[] is not an object[]; that isn't how array variance works - so: if you pass a DateTime[] array to string.Format, it isn't using the Format(string, object[]) overload - you're effectively using passing the entire DateTime[] as a single object to Format(string, object), hence from Format's perspective, you can only use token 0.

    Basically, use:

    var array = new object[] {
           new DateTime(2000, 1, 1),
           new DateTime(2010, 12, 31)
    };
    

    and it should work.

  • answered 2020-03-31 09:33 oleksa

    var format = "{0:MMM}{1:MMM}"; expects three arguments supplied for string.Format() - one for format and two arguments for values.

    Like

    string.Format(format, array[0], array[1])
    

    another option is to change array from DateTime[] to object[] array