1

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • as i know this will work propertly – Pranay Rana Sep 20 '11 at 07:35
  • @Jon - I was just wondering if there's a library support for that, or should I write as I did. – MByD Sep 20 '11 at 07:36
  • But obviously you do have access to the internet and MSDN online, http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx. There is no `InsertFormat` method. – Jodrell Sep 20 '11 at 07:36
  • @Pranay Rana - thanks, I know, I meant something like `AppendFormat` – MByD Sep 20 '11 at 07:37
  • @Jodrell - That's a fair comment, yet I thought I might be missing something. – MByD Sep 20 '11 at 07:38
  • @MByD, perhaps in .Net 5.0 although, I don't recall ever calling `StringBuilder.Insert`, it always seemed more efficient to `Append` – Jodrell Sep 20 '11 at 07:43

2 Answers2

3

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); 
meziantou
  • 20,589
  • 7
  • 64
  • 83
1

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.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • 1
    The extension method is probably the best suggestion here, but I feel this is technically not a good answer because the question specifically stipulates "system library method". – Jon Sep 20 '11 at 07:40
  • @Jodrell - No is a legit answer :). BTW why append seems more efficient to you? – MByD Sep 20 '11 at 07:46
  • @MByd, internally the string array is some buffer of chars, when you `Append` the new chars are written to the end (if there is not enough space the buffer is extended.) When you `Insert`, a space is made by shifting all the "after" chars up the buffer and the new chars go in the gap. It is possible that the implementation could be some sort of linked list but that sounds too ineffiecient, in general, to be true and I believe that I've read that that is no the case. – Jodrell Sep 20 '11 at 08:01
  • further to previous comment http://stackoverflow.com/questions/6524240/how-does-stringbuilder-work, note the last post http://1024strongoxen.blogspot.com/2010/02/net-40-stringbuilder-implementation.html which suggests it may actually be a linked list now. – Jodrell Sep 20 '11 at 08:08