When to use string classes in C#?

  • C/++/#
  • Thread starter mcodesmart
  • Start date
  • #1
34
0
We have a string builder class which is mutable in C#. Why do we need immutable string classes?
 

Answers and Replies

  • #2
AlephZero
Science Advisor
Homework Helper
6,994
293
Basically, for efficiency. for example the immutable classes can share storage for identical objects. Harmless-looking statements in an object oriented language can often create and destroy temporary objects, and the overheads are much smaller if the contents of these are known to be immutable.

You should only use mutable strings if you know the contents of the string may change after you have created it.
 
  • #3
harborsparrow
Gold Member
611
154
A StringBuilder class just pre-allocates a big array to hold the characters of a string you are yet to create. It prevents the need to call the allocator over and over again if concatenating a bunch of (immutable) shorter strings.

When there is a LOT of string concatenation going on at runtime, it is often more efficient (significantly more) to use StringBuilder.
 

Related Threads on When to use string classes in C#?

Replies
6
Views
5K
Replies
1
Views
6K
Replies
18
Views
443
  • Last Post
Replies
3
Views
15K
  • Last Post
Replies
3
Views
19K
  • Last Post
Replies
23
Views
7K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
9
Views
2K
Replies
2
Views
947
Top