Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to string

URL is a string, so why can't I concatenate like so:

string url = "something";
url + string.Format("group={0}&", Id);

Is this because string is a reference type, and it's actually trying to add it to the reference rather than the object?

What is the best way to achieve what I want?

like image 289
m.edmondson Avatar asked Sep 12 '26 08:09

m.edmondson


2 Answers

Needs assignment

url += string.Format("group={0}&", Id);

or

url = url + string.Format("group={0}&", Id);
like image 150
Joe Avatar answered Sep 13 '26 21:09

Joe


The + operator doesn't change the variable that you use in the expression. It doesn't do that for a numeric value either:

int i = 42;
i + 4; // doesn't change the variable i

You have to assign the result to a string variable:

url = url + string.Format("group={0}&", Id);

You can also use the += operator, that will produce the exact same runtime code:

url += string.Format("group={0}&", Id);

Note that this doesn't change the string, it produces a new string from the two strings. What the code actually does is:

string temp = String.Concat(url, string.Format("group={0}&", Id));
url = temp;
like image 42
Guffa Avatar answered Sep 13 '26 21:09

Guffa