StringBuilder vs string constructor - character

I just saw code like

StringBuilder result = new StringBuilder(); for (int i = 0; i < n; i++) { result.Append("?"); } return result.ToString(); 

I know that concatenation with StringBuilder counts faster (and does not create a new string instance for every addition). But is there any reason why we would not want to write

 return new string('?', n) 

instead

+7
source share
2 answers

But is there any reason why we would not want to write return new string("?", n) instead

The only reason I can think of this is the developer’s ignorance with the existence of this string constructor . But for people familiar with this, no, there is no reason not to use it.

Also, you probably meant:

 return new string('?', n) 
+7
source

The main reason not to use new string("?", n) is that such a constructor does not exist and it will not compile. However, there is no reason not to use new string('?', n) , and I totally urge you to do this.

+4
source

All Articles