C# Best practices – String

Few things I want to point out when using string in C#.

In C# so as Java, string is immutable. what does it mean by immutable? immutable is that once an object have a value it never changes. For example, when you have a value ‘unni’ assigned to ‘name’ variable, and later if you decide to change the name ‘unni’ to say ‘nair’, then when you assign the value to ‘name’ variable, it creates new memory and put the value ‘nair’ in it and point to that location. The important point in here is that, the value ‘unni’ never got overwritten. That memory location now becomes garbage for garbage collector to pick it up. So you have be very careful when using string, always mindful of its immutability so that you will not create too many garbage memory so fast. You can think of immutability like ‘const’ or ‘readonly’ keyword in C#. One of the main benefit most of developers do not know is that immutability is that it naturally lend it self to concurrent programming.

Now that we know what is immutability, where could this cause problems for the novice programmers; Lets take the following code.

            string concatinatedString = string.Empty;
            for (int i = 0; i < 10; i++)
                concatinatedString += i.ToString();

This code does not look harmful. But if we go back to the example with my name what really happening is, the look is going to create 10 instance of the string variable each one with its previous string + current value.So when the program runs, you can see, it created 10 memory objects even though expected task was to append all numbers to the same variable.


Now the question is, but I want to create a concatenated string so how do I go about doing it? The answer is very simple, use StringBuilder. By definition, this is mutable string of characters. So if any point you want to create mutable strings, try to use string builder. So the above code if we would use StringBuilder, it will be like the following

            StringBuilder concatinatedString = new StringBuilder();
            for (int i = 0; i < 10; i++)

Even though we have lot more memory to work with compared to old days, we should take every possible step to write an efficient code.