A. Woods A. Woods - 2 months ago 6
C# Question

multiplying a variable without rewriting it

So I am fairly new to the "code world" and hopefully have a fairly simply question.

txtBox.Text = "x";


How would I make it so I am able to see 10 X's in my
txtBox
without completely writing it out?

Answer

string has a constructor that repeats a character for a given number of times:

txtBox.Text = new string('x', 10);

It's documented here.

If what you want to repeat is a string (not a single character) you need a loop, but use a StringBuilder to minimise memory fragmentation. Try avoiding repetitive string concatenations:

var stringBuilder = new StringBuilder();
for(int i = 0; i < 10; i++)
    stringBuilder.Append("ThePatternToRepeat");

txtBox.Text = stringBuilder.ToString();