Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does String.Format Discriminate? [duplicate]

Tags:

c#

.net

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?

like image 901
Brent Arias Avatar asked Feb 24 '26 12:02

Brent Arias


2 Answers

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.

like image 106
Chris Avatar answered Feb 26 '26 01:02

Chris


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

like image 25
Nikita Avatar answered Feb 26 '26 01:02

Nikita