c# repeat character x times code example

Example 1: C# repeat x times

// Normally in a namespace, of course.
public class LoopUtilities
{
    public static void Repeat(int count, Action action)
    {
        for (int i = 0; i < count; i++)
        {
            action();
        }
    }
}

using static LoopUtilities;

// Class declaration etc, then:
Repeat(5, () => Console.WriteLine("Hello."));

Example 2: c# repeat string x times

string result = new String('-', 5);
Output: -----

Example 3: how to write a method that returns a string that copies itself times n

public static String repeat(String s, int n) {    StringBuilder sb = new StringBuilder(str.length() * n);    for (int i = 0; i < n; i++)        sb.append(s);    return sb.toString();} public static void main(String[] args) {    System.out.println(repeat("ha", 5));}