Be aware that C# strings are immutable

1 sept.

In C# (and maybe other development platforms like Java, I don’t know) the strings are immutable, which means that every time you do an operation with strings (like +=) in fact the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to the initial one.

Immutable string example
  1. private void foo()
  2. {
  3.     string b = „f”;
  4.     b += „elix”;
  5. }


In the above example, after line #3 string „f” will be eligible for garbage collection.

What does this means?

Well, if you need to create some long strings and you use += to concatenate then in the end you will have a lot of candidates for garbage collection thus making your computer memory fill up with junk.

Does you app throws an Out Of Memory Exception? Search for string manipulation first. By the way, interview question: if there is no more memory to be allocated, how could it be that the system still has memory to create a Out Of Memory Exception object? (answer in another post).

The fix for this?

There is no problem in using strings but there are cases (like creating an in memory long, long text which will be later on sent to DB) when StringBuilder would be the appropriate method to use. Or streams. Do not rely on GC to collect your garbage.

Fun(?) facts

  1. although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.
  2. strings aren’t value types since they can be huge, and need to be stored on the heap.
  3. in .NET string is an alias for String.
  4. since strings are immutable then they are thread safe. Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
  5. Verbatim string are the ones that are prefixed with @„c:\Docs\Source\a.txt”. The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
Nu fi egoist, dă mai departe să ajungă la tot poporul

One Reply to “Be aware that C# strings are immutable”

  1. Pingback: Have you heard about WinDbg? — Felix Vătuiu

Lasă un răspuns

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.