How to work properly with strings in C#?
c#, string
Solution
You are correct in that the operations you're performing are creating new strings, and not mutating a single string.
You are incorrect in that this is generally problematic or something to be avoided.
If your strings are hundreds of thousands of characters, then sure, copying all of those just to remove a few leading spaces, or to add a few characters to the end of it (repeatedly, in a loop, in particular) can actually be a problem.
If your strings aren't large, and you're not performing many (an in thousands of) operations on the string, then you almost certainly don't have a problem.
Now there are a handful of contexts, generally rather rare, that do run into problems with string manipulation. Probably the most common of the problematic contexts is appending a bunch of strings together, as doing so means copying all of the previously appended data for each new addition. If you're in that situation consider using something like a `StringBuilder` or a single call to `string.Concat` (the overload accepting a sequence of strings to concat) to perform this operation.
Other contexts are, for example, programs dealing with processing DNA strands. They'll often be taking strings of millions of characters and creating hundreds of thousands of many thousand character long substrings of that string. Using standard C# string operations would therefore result in a lot of unnecessary copying. People writing such programs end up creating objects that can represent a substring of another string without copying the data and instead referring to the existing string's underlying data source with an offset.
Problem
I know there is a rule about strings in C# that says: When we create a textual string of type string, we can never change its value! When putting different value for a string variable thje first string will stay in memory and variable (which is kind of reference type) just gets the address of the new string. So doing something like this: ``` string a = "aaa"; a = a.Trim(); // Creates a new string ``` is not recommended. But what if I need to do some actions on the string according to user preferences, like so: ``` string a = "aaa"; if (doTrim) a = a.Trim(); if (doSubstring) a = a.Substring(...); etc... ``` How can I do it without creating new strings on every action ? I thougt about sending the string to a function by ref, like so: ``` void DoTrim(ref string value) { value = value.Trim(); // also creates new string } ``` But this also creates a new string... Can someone please tell me if there is a way of doing it without wasteing memory on each action ?