Introduction
Making mistakes is inevitable in programming. Even a small mistake could prove to be very costly. The wise thing is to learn from your mistakes and try not to repeat them.
In this article I will be highlighting the one of the mistakes which I consider to be the most common mistake made by C# developers.
Formatting a string
There lies the strong possibility of making costly mistakes while working with string types in C# programming. String is always an immutable type in the .NET Framework. When a string is modified it always creates a new copy and never changes the original. Most developers always format the string as shown in the sample below
<br />
string updateQueryText = "UPDATE EmployeeTable SET Name='" + name + "' WHERE EmpId=" + id;<br />
<br />
The above code is really messy and also as the string is immutable it creates 3 unnecessary garbage string copies in the memory as a result of multiple concatenations.
The better approach is to use string.Format as it internally uses StringBuilder which is mutable. It also paves the way for a clean code.
<br />
string updateQueryText = string.Format("UPDATE EmployeeTable SET Name='{0}' WHERE EmpId={1}", name, id);<br />
Keep watching for some more tips....
Eswar