Shachaf.Gortler
Shachaf.Gortler

Reputation: 5735

StringBuilder AppendFormat IEnumarble

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

Upvotes: 0

Views: 939

Answers (3)

Raktim Biswas
Raktim Biswas

Reputation: 4077

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.

Upvotes: 0

jonh
jonh

Reputation: 254

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

Upvotes: 1

Yacoub Massad
Yacoub Massad

Reputation: 27861

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

Upvotes: 2

Related Questions