Link to home
Start Free TrialLog in
Avatar of QPR
QPRFlag for New Zealand

asked on

When to use string.format

I'm playing around with some c# sample code...
At one point int the code I need to use string.format() in order to build a string and have the text value of the variable inserted in place. If I don't do this I get an error.

Later on in the code I am concatonating a variable's value with a string and I'm not forced to use string.forrmat as everything glues together as expected.

I have put the 2 pieces of code in the code window so you can see what I am talking about.
All I can think is that in the first instance I am replacing a placeholder with a variable's value but in the second instance I am simply putting 2 strings (1 a variable's value and 1 a hard coded string) end to end.
Is my thinking correct?

Does string.format look for {0} in the first argument and replace it with the value of the second argument?
string subcategory = listCategories.SelectedItem.Text;       
string query = "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Text'>{0}</Value></Eq></Where></Query>";
query = string.Format(query, subcategory);

-----

public partial class FullList : System.Web.UI.Page
{
    private const string url = "http://MyServer";
    private Lists Proxy;

    protected void Page_Load(object sender, EventArgs e)
    {
        Proxy = new Lists();
        Proxy.Url = url + "/_vti_bin/lists.asmx";

    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of cyberkiwi
cyberkiwi
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Cyberkiwi,

>>It's a matter of preference whether to use String.Format or concatenate  stuff together.

I beg to differ from your opinion. This is not a matter of preference. String concatenation (using '+') should be avoided as much as possible.

Strings are immutable types, meaning once assigned a memory location, they cannot be modified in place. It creates a new string every time you 'append' characters to an existing one. This causes a performance hit in your code and that's the reason to avoid it. Using string.format() IS a better way to go.

http://support.microsoft.com/kb/306822 talks about another option of using a StringBuilder class that pretty much does the same thing as string.format, but I have a read of some articles where people have seen string.format to perform better than the StringBuilder class, but haven't tested it myself.

So all in all - avoid string concatenation and use string.format or StringBuilder class.

Arun
Also take a look at String.Concat().

example
String.Concat("myid=", 1);

so you don't have to convert the int to a string.
Avatar of QPR

ASKER

thanks, you confirmed what string.format() does for me