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()


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(

in the DataBinding event of the password label control.

5 Responses to Replicate String in C#

  1. Chris says:

    Wouldn’t string s = new string(‘*’, count); do the job a little more clearly?

  2. devio says:

    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.

  3. StewartFip says:

    Found this at:

    new System.Text.StringBuilder().Insert(0,”myString”,count).ToString()

    Worked like a charm for me.

  4. […] String in C# My original posting on string repetition caused a couple responses, and is currently among the Top Posts, which indicates to me that this […]

Leave a Reply

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

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

Google photo

You are commenting using your Google 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.

%d bloggers like this: