Strings in C# - Some handy rules of thumb

I don't often write as much C# as I used to, but occasionally I work on legacy tech or help other Windows shops learn more about modern ways of using C# like using dependency injection, test-driven development, etc. Sometimes I work with non-Windows programmers to teach them to use C#.

So this is an oldie, but here's a quick string lesson for those of you who may be learning C# or coming from another language.

string.Format() is meant for efficient string replacement, and its parameters are automatically ToString()'d.

DON’T:
string.Format(“stuff”)  
string.Format(“stuff {0}”, something.ToString())  
string.Format(“stuff {0}”, something + “ “ + something_else)  
DO:
“stuff” //use a literal and drop the non-functional string.Format()

string.format(“stuff {0}”, something) //drop the .ToString()

string.format(“stuff {0} {1}”, something,something_else) //use multiple parameters rather than nesting more concatenation.  

If you find yourself continually appending to a string via concatenation, there's a handy class in C# that works like a string buffer called StringBuilder which will allow you to do this more efficiently. It has a few handy methods like: AppendFormat(“{0} {1}”, paramA,paramB) or AppendLine(“string literal”). There's no shame in combining them into: AppendLine(string.Format("text {0}",params)) either.

With AppendLine or System.Environment.NewLine you don’t need to add the newline manually and it's platform agnostic (*nix or Windows). But just for reference: newlines (on windows) are always \r\n, and on most other platforms just: \n.

Enjoy!