When to use string classes in C#?

  • Context: C# 
  • Thread starter Thread starter mcodesmart
  • Start date Start date
  • Tags Tags
    Classes String
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
mcodesmart
Messages
34
Reaction score
0
We have a string builder class which is mutable in C#. Why do we need immutable string classes?
 
Physics news on Phys.org
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.
 
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.