MByD
MByD

Reputation: 137312

Insert Formatted String to StringBuilder

Is there a (system library) way to insert a formatted string to a StringBuilder that will be identical to the following?

myStringBuilder.Insert(0, string.Format("%02X", someInt)); 

I haven't find any in the class documentation.

Upvotes: 1

Views: 1252

Answers (2)

meziantou
meziantou

Reputation: 21337

You can create an extension method

public static StringBuilder InsertFormat(this StringBuilder sb, string format, params object[] args)
{
    sb.Insert(0, string.Format(format, args)); 
}

Then you can write

myStringBuilder.InsertFormat("%02X", someInt); 

Upvotes: 3

Davide Piras
Davide Piras

Reputation: 44605

StringBuilder provides you the method AppendFormat which does the append and the format in one call but adds the content in the end of the buffer.

In your specific case since there is no provided .NET framework method which does InsertFormat as you wish you either use the method shown above in your question or create an extension method (for example call it InsertFormat) and then use it in your project.

Upvotes: 1

Related Questions