Thursday, August 6, 2009

Using String.Format...Or parameterizing strings

Say you have an operation that requires a string that has a couple of values that change depending on variables. For instance, some console output or a SQL query. You may have used string concatenation which looks like this:
string strOutput = "You entered in: " + strInput + ". Thanks for playing!";

//this would assign strOutput the following value (if strInput == "I quit"):
//You entered in: I quit. Thanks for playing!
To improve code readability, I've found that parameterizing the string using string.Format is very useful. Instead of breaking up the string, put a set of curly brackets around the zero-based index of the string parameter you want to appear at the location of the curly brackets. Using the same example as above:
string strOutput = string.Format("You entered in: {0}. Thanks for playing!", strInput);
It's a simple change that can make a huge difference when you have to go back and change things. It shortens the strings and makes it easier to find the variables.

Remember, your code is never perfect, more importantly your requirements are never static, always code in such a way that it is easy understand and change at a later date.

No comments:

Post a Comment