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.”

做~自己de王妃 提交于 2020-01-03 00:56:27

问题


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..


回答1:


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.




回答2:


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]);


来源:https://stackoverflow.com/questions/27721685/exception-while-using-string-format-index-zero-based-must-be-greater-than-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!