8

Is there a succinct way (i.e. not a for loop) to create a string of a specified length? Doesn't matter what is in the string.

2
  • 3
    It always matters what's in a string, because you can't change it later. Commented Aug 21, 2009 at 17:02
  • 1
    I am unit testing string length validation - the contents don't apply in this case. Commented Aug 21, 2009 at 17:04

3 Answers 3

35

You can use the string constructor that takes a char and an int. It creates a string instance with the char repeated the specified number of times.

Sign up to request clarification or add additional context in comments.

Comments

12

As bdukes mentions there's constructor, that takes a char and an int. That will construct a string of the given length filled with the char.

However, keep in mind, that strings are immutable in .NET, so if you want to create a specific string buffer, you should use StringBuilder instead.

Comments

-3

why would you want to create a string if you dont want to control what the value of the string would be?

I would suggest using a StringBuilder and using the constructor that takes an int

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.