Shachaf.Gortler Shachaf.Gortler - 3 months ago 24
C# Question

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

Answer

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