String.Format will happily work correctly with an array of strings, but fails when dealing with an array of ints with exception :
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
string result = null;
var words = new string[] { "1", "2", "3" };
result = String.Format("Count {0}{1}{2}", words); //This works.
var nums = new int[] { 1, 2, 3 };
result = String.Format("Count {0}{1}{2}", nums); //This throws an exception.
Why is this so?
This happens because the string.Format overload you are using wants object[]. A string is a reference type, so string[] can be implicitly cast to object[], but int is a value type, and would have to be boxed before being put in an array of objects. So when you're using int it selects another overload that just takes one parameter, and then passes the entire int[] as a single object instead of passing each int by itself.
Because ToString() method is called for Array of ints. And it's becomes 1 object. This code:
var nums = new int[] { 1, 2, 3 };
result = String.Format("Count {0}", nums);
Will result: Count System.Int32[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With