Replicate String in C#

I was surprised to find that the string class in C# does not have a Replicate() method.

The fastest way (in terms of lines of code) to replicate a given string seems to be a combination of string.Concat() and ArrayList.Repeat()

string.Concat(System.Collections.ArrayList.Repeat(SourceString,
NumberOfRepetitions).ToArray());

For example, if you want to indicate that a password has been provided, but should not be displayed (obviously!), use the line

LabelPassword.Text = string.Concat(
System.Collections.ArrayList.Repeat('*',
LabelPassword.Text.Length).ToArray());

in the DataBinding event of the password label control.

5 thoughts on “Replicate String in C#

  1. Thank you Chris,

    that was *what* I was looking for, but not *where* I was looking. As you can see from my entry, I expected a method or a static method.

    I checked now why I did not find this information myself. After pressing F1 on the “string” keyword in VS, you need FOUR clicks to get to the string() constructor, and only if you know where you want to end up!

    Also the string constructor only allows a char parameter (which is sufficient for the current example), but no string.

  2. Pingback: Replicate String in C# « devioblog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.