0

I have a string builder and a list of object ,

int[] values = new int[] {1,2};
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}, {1}", values );

I see an IntelliSense error

None existing arguments in format string

why am I seeing this error ,and how should I I use a list parameters inside the AppendFormat

Shachaf.Gortler
  • 5,655
  • 14
  • 43
  • 71

3 Answers3

2

The overload of AppendFormat that you are currently using (or that the compiler decided to use) has the following signature:

public StringBuilder AppendFormat(string format, object arg0)

It is expecting a single argument and therefore a format that contains two arguments ("{0}, {1}") is invalid.

Your intention is to pass the array as multiple arguments, the overload that you need to use is the following:

public StringBuilder AppendFormat(string format, params object[] args)

Note that the second argument is an object[], not int[]. To make your code use this overload, you need to convert the int array into an object array like this:

builder.AppendFormat("{0}, {1}", values.Cast<object>().ToArray());
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1

You need to pass in an object array instead of an int array. Otherwise it thinks the array object is the parameter for arg0.

object[] values = new object[] { 1, 2 };
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}, {1}", values);
jonh
  • 233
  • 1
  • 10
0

You need to loop through the list using foreach

int[] values = new int[] {1,2};
StringBuilder builder = new StringBuilder();
foreach (int val in values)
{
    builder.AppendFormat("{0}\n", val);         
}
Console.WriteLine(builder);

See the Working Fiddle.

In your case, you used:

builder.AppendFormat("{0}, {1}", values );

as you are passing 2 arguments {0}, {1} which is invalid for a single value of values as the outcome.

Blue
  • 22,608
  • 7
  • 62
  • 92
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32