MR.G MR.G - 9 months ago 44
C# Question

+= symbol's difference in string and textbox

Sorry for asking this silly question. I have a string msg+="hi"; and a button to print that message using label. No matter how many time I pressed the button the label display "hi" only one time. Another thing is i have a label1.text += textbox.text; if click the button it display the message entered by user many time based on the number of clicks. Can someone explain me what is difference storing a message in string then display it using label and straight away display t using label.

string msg += "hi";
label1.text = msg;

output: hi
//button clicked many times but only one output

label1.text += textbox.text;
//that I input = hi!
//button I clicked 4 times
output = hi! hi! hi! hi!

Answer Source

When you press button and you call method that use

string msg += "hi";

you actually still make new instance of msg and insert "hi".

But when you press button and you have in textbox string "hi" and you call method that use

label1.text += textbox.text;

you don't instantiate something, you just insert "hi" after string that is in label1.text.

It is because msg is local variable and label1.text is global variable (that's why you don't instantiate it all the time).