string.Repeat() – smaller and faster version

Yesterday I wrote about Repeat extension method for strings. Today I offer you shorter and faster version of it.

public static string Repeat(this string instr, int n)
if (string

var result = new StringBuilder
(instr.Length * n);
return result.Insert(0, instr, n).ToString();

If you look at the code then you can see that it is possible to avoid writing Repeat method, but you have to pay in readability. Take a look at the following line:

var x = new StringBuilder(instr.Length * n)
                        .Insert(0, instr, n)

See also

Leave a Reply

Your email address will not be published. Required fields are marked *