Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Useful method – 1 of N – Multiply string June 13, 2008

Filed under: C# — ppetrov @ 11:26 am
Tags:

Here is an extension method on the string class. We can generate strings that can be used in many scenarios.

public static string Times(this string value, int n)
{
    return value.Times(n, string.Empty);
}

public static string Times(this string value, int n, string separator)
{
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    if (n < 0)
    {
        throw new ArgumentException("Must be a positive number.", "n");
    }
    if (value.Length > 0 && n > 0)
    {
        return string.Join(separator, Enumerable.Repeat(value, n).ToArray());
    }
    return value;
}

Possible usage can be:

            string sample = "many";
            string value = word.Times(3, ", ");
            // value = "many, many, many"

or probably this:

            string sample = "+-";
            string value = sample.Times(30);
            // value = "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-"

Of course we can chain the Times() method. Doing so we can have some interesting results:

            string sample = "5";
            string value = sample.Times(2).Times(2, ", ").Times(2, "-").Times(2, ":");
            // value = "55, 55-55, 55:55, 55-55, 55"