When to use string classes in C#?

  • C/++/#
  • Thread starter mcodesmart
  • Start date
  • #1
34
0

Main Question or Discussion Point

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
291
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
534
108
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#?

  • Last Post
Replies
3
Views
15K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
23
Views
7K
  • Last Post
Replies
3
Views
19K
  • Last Post
Replies
9
Views
2K
Replies
2
Views
853
Replies
14
Views
3K
Replies
5
Views
4K
Replies
8
Views
4K
Replies
9
Views
717
Top