Thursday 15 January 2009

String.Format()

When concatenating strings you can use the String.Format() method rather than adding seperate strings.

String.Format() is based on the StringBuilder class and, as such, allows you to concatenate strings with the added performance of the StringBuilder class.

Example:

int intOne = 22;
String strTwo = "Donald";
String result = String.Format("{0} is {1} years old on {3}", strTwo, intOne, dataSet.Tables["Employee"].Rows[0]["DOB"].ToString());


You can have any number of parameters, they must be passed in the correct order, e.g. first parameters replaces {0}, second parameter replaces {1} etc.

This gives the same results as the following but performance wise it is better because the compiler doesn't destroy and recreate lots of String objects.:

String result = strTwo + " is " + intOne + " years old on " + dataSet.Tables["Employee"].Rows[0]["DOB"].ToString;

No comments:

Free Hit Counter