Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,357 Categories: 12

Total Tutorial Views: 42,397,244

[C#] String Concatenation with Placeholders

Tutorial Name: [C#] String Concatenation with Placeholders  

Category: PC Tutorials

Submitted By: Skittle

Date Added:

Comments: 0

Views: 422

Related Forum: PC Building Forum

Share:

String Concatenation is a method of merging strings and values together to get one string in the end. You could do it like this, which is quite inefficient:

int a = 1;
int b = 2;
int c = 3;
string finishedString;
finishedString = "a = " + a + ", b = " + b + ", c = " + c;
//finishedString = "a = 1, b = 2, c = 3"

This is not the best way to go about merging the variables together as it is quite lengths and will take even longer the more values you have. There is a Function called Format which you can use to make this a whole lot simpler, here is how you would use it to get the same output as the first method:

int a = 1;
int b = 2;
int c = 3;
string finishedString;
finishedString = string.Format("a = {0}, b = {1}, c = {2}", a, b, c);
//finishedString = "a = 1, b = 2, c = 3"

This may look more complicated, but it is actually quite simple. You may be wondering, "What do the {0} things do?" The Braces with the numbers inside them are called placeholders, they do not show up in the final string, they are substituted with a different value. As you can see, we have three placeholders ranging from 0 - 2, these will be substituted with our a, b and c variables, like so:
Placeholder | Variable
{0} | a
{1} | b
{2} | c
The place where we want to have the variable a in our string is accompanied by the {0} placeholder! and the same with the other variables. The format of this Function is quite simple, we have the final string with the placeholders as the first parameter, and then the variables we want to substitute in the order. If we only had one variable called myVariable, we would only need one placeholder, {0}, as we start from zero instead of one. This is the code for that example:

string myVariable = "This is a variable";
string finishedString;
finishedString = string.Format("{0}", myVariable);
//finishedString = "This is a variable";

I hope that I have explained this well, it is very simple to understand yet quite difficult to explain. If you have any questions, feel free to PM me

Ratings

Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"[C#] String Concatenation with Placeholders" :: Login/Create an Account :: 0 comments

If you would like to post a comment please signin to your account or register for an account.