Tuesday, June 12, 2007

Pretty good C# string concatenation

I have discovered a pretty cool way of concatenating strings in C#.

Here is the code snippet:

List<string> list = new List<string>();
list.Add("Some ");
list.Add("string ");
list.Add("to be concatenated");

string res = String.Join(String.Empty, list.ToArray());

And here you have an equivalent of StringBuilder, except, you are not working with a character buffer, but with an array of strings. This is more efficient than StringBuilder, if you don't know how many concatenations will be done or how big the resulting string is going to be.
The ToArray is not going to linearly create and copy elements to a string[] array, apparently C# is doing it directly behind the scenes.

You can do the same with an ArrayList and cast the result of it's ToArray() to (string[]). I tried both. If you do know how big the string is going to be, then the StringBuilder is going to be more efficient (just remember to specify the initial capacity, he he ;) otherwise it won't be!)

Hope you might find it useful.

3 comments:

Anonymous said...

very nice !!

Justin said...

Thanks! Just had to use this today!

Sujeet said...

useful.