user2740190
user2740190

Reputation:

Using placeholder in StringBuilder

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?

Upvotes: 2

Views: 3297

Answers (4)

Ian R. O'Brien
Ian R. O'Brien

Reputation: 6920

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.

Upvotes: 8

Hassan
Hassan

Reputation: 5430

Use string.Format

 builder.Append(string.Format("Export: Processed {0} Teacher(s)", processed));

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You need to use AppendFormat; also, calling ToString on the processed is not necessary:

builder.AppendFormat("Export: Processed {0} Teacher(s)", processed);

Upvotes: 4

Cam Bruce
Cam Bruce

Reputation: 5689

There is no overload for StringBuilder.Append(string, string)

Use StringBuilder.AppendFormat(string, object) instead.

Upvotes: 4

Related Questions