Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using placeholder in StringBuilder

Tags:

c#

I have something like this:

int processed = 123;
//
....
builder.Append("Export: Processed {0} Teacher(s)", processed.ToString());

But it doesn't compile and says "String is not assignable to char."

What is wrong?


1 Answers

If you want to pass in a format string to your StringBuilder you have to call the AppendFormat overload passing in your format string. Also the .ToString() call is unnecessary since AppendFormat will implicitly call .ToString() on each parameter. Therefore your solution can be written as follows:

StringBuilder builder = new StringBuilder();
int processed = 123;
builder.AppendFormat("Export: Processed {0} Teacher(s)", processed);

From the MSDN documentation

Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding object argument. This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

like image 69
Ian R. O'Brien Avatar answered Mar 29 '26 20:03

Ian R. O'Brien