When to use string classes in C#?

  • C/++/#
  • Thread starter mcodesmart
  • Start date
  • #1
mcodesmart
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
7,002
297
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
613
155
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.
 

Suggested for: When to use string classes in C#?

  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
6
Views
6K
Replies
1
Views
2K
  • Last Post
Replies
2
Views
7K
  • Last Post
Replies
5
Views
4K
  • Sticky
  • Last Post
2
Replies
42
Views
6K
  • Last Post
Replies
27
Views
21K
  • Last Post
Replies
2
Views
910
  • Last Post
Replies
8
Views
5K
  • Last Post
Replies
3
Views
15K
Top