Using an array as an argument to string.Format ()

When I try to use an array as an argument to the string.Format() method, I get the following error:

FormatException: The index (based on zero) must be greater than or equal to zero and less than the size of the argument list.

The code is as follows:

 place = new int[] { 1, 2, 3, 4}; infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place); 

The array contains four values, and the arguments in string.Format() also match.

What causes this error?

( infoText.text is just a regular String object)

+7
string arrays c # string-formatting
source share
4 answers

You can convert an int array to a string array, how to pass it.

 infoText.text = string.Format("Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place.Select(x=>x.ToString()).ToArray()); 
+3
source share

Quick fix.

 var place = new object[] { 1, 2, 3, 4 }; 

C # does not support converting a covariant array from int[] to object[] , so the whole array is treated as object , hence this overload with one parameter.

+7
source share

You can pass an explicit array for the params argument, but it must have a match type. string.Format has several overloads, of which we are interested in the following two:

 string.Format(string, params object[]) string.Format(string, object) 

In your case, handling int[] as object is the only conversion that works, since int[] cannot be implicitly (or explicitly) converted to object[] , so string.Format sees four placeholders, but only one argument. You will need to declare your array of the correct type.

 var place = new object[] {1,2,3,4}; 
+3
source share

As already mentioned, you cannot convert int[] to object[] . But you can fix this problem using Enumerable.Cast<T>() :

 infoText.text = string.Format ( "Player1: {0} \n Player2: {1} \n Player3: {2} \n Player4: {3}", place.Cast<object>().ToArray() ); 

By the way, if you are in C # 6 or higher, you can use interpolated strings instead of string.Format :

 infoText.text = $"Player1: {place[0]}\n Player 2: {place[1]} \n Player 3: {place[2]} \n Player 4: {place[3]}"; 
+2
source share

All Articles