Reputation: 2956
I just saw a code like
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++)
{
result.Append("?");
}
return result.ToString();
I know that concatenating with StringBuilder is considered faster (and does not create new instance of a string on every append). But is there any reason we would not prefer to write
return new string('?', n)
instead?
Upvotes: 7
Views: 477
Reputation: 1064114
The main reason not to use new string("?", n)
is that no such constructor exists and it won't compile. However, there is absolutely no reason not to use new string('?', n)
, and I fully encourage you to do so.
Upvotes: 4
Reputation: 1039458
But is there any reason we would not prefer to write
return new string("?", n)
instead
The only reason I can think of is unfamiliarity of the developer with the existence of this string constructor. But for people familiar with it, no, there is no reason to not use it.
Also you probably meant:
return new string('?', n)
Upvotes: 7