Akshatha
Akshatha

Reputation: 642

Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."

I have an array

ArrayList array = new ArrayList();
array.Add("a");
array.Add("b");
array.Add("c");

and I have a string variable refFormat which has the format as below.

string refFormat = "{2} {0}";

I'm trying to get a string of values from the array with this format. Below is what I have written.

string newStr = String.Format(refFormat,array.ToArray());

I'm getting the following exception when I'm trying to do this.

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

I know this question sounds repeated but my doubt is how to pick the values from the array whose indexes are the ones specified in the format that 2 and 0. Please help..

Edit: Hi sorry for putting up the wrong question. I'm using an arraylist instead of a string array I'm trying the same. I'm still getting the exception in spite of converting it to an array using ToArray(). Where am I going wrong? And also I cannot use List instead of arraylist here since the array contains data of different type. Please help me out..

Upvotes: 1

Views: 22013

Answers (3)

NNSkelly
NNSkelly

Reputation: 71

For string arrays, I see no reason the syntax shouldn't work. I had the same issue, however, with an int array, and that gets gnarly. Tl;dr: int is not an object type, so it will never resolve to the open-ended (string format, params object[] args) overload and instead tries to use (string format, object arg0) overload. Broader discussion and some theoretical workarounds at Using an array as argument for string.Format()

Upvotes: 0

Jason Evans
Jason Evans

Reputation: 29186

For reference, here is my working code too:

string[] array = new string[] { "a", "b", "c", "d" };

string refFormat = "{2} {0}";

string newStr = String.Format(refFormat, array);

Console.WriteLine(newStr);

I did not encounter an error when running the above code.

Upvotes: 5

Tushar Gupta
Tushar Gupta

Reputation: 15923

You are not giving the parameters correctly , it needs to be indexed as {0} {1} and so ons

String.Format(refFormat,array[2],array[0]);

Upvotes: 0

Related Questions