- Back to Home »
- C# Tutorial »
- Concatenation in C#
Posted by : senan
Friday, February 14, 2014
Another thing we can do is something called Concatenation. Concatenation
is joining things together. You can join direct text with variables, or join
two or more variables to make a longer string. A coding example may clear things
up.
Delete the two new lines you've just added. Now add a second variable, just
below the first one:
string messageText;
So you coding window should look like this:
We want to store some text inside of this new variable, so add the following
line of code just below string messageText:
messageText = "Your name is: ";
Your code window will then look like ours below:
When the message box displays, we want it say some thing like "You name
is John". The variable we've called messageText holds the first
part of the string, "Your name is ". And we're getting the persons
name from the text box:
firstName = textBox1.Text;
The person's name is being stored in the variable called firstName.
To join the two together (concatenate) C# uses the plus symbol ( + ).
messageText + firstName
Instead of just firstName between the round brackets of MessageBox.Show(
), we can add the messageText variable and the plus symbol:
MessageBox.Show(messageText + firstName);
Amend your MessageBox line so it's the same as the one above. Here's the coding
window:
Run your programme. Type your first name into the text box, and then click
your button. You should see something like this:
So we set up a variable to hold some direct text, and got the person's name
from the text box. We stored this information in two different variables. To
join the two together, we used the plus symbol. We then displayed the result
in a message box.
But you can also do this:
MessageBox.Show( "Your name is: "
+ firstName);
Here, we're not storing the text in a variable called messageText. Instead,
it's just direct text surrounded by double quotes. Notice, though, that we still
use the plus symbol to join the two together.