1

I am wondering what the difference is if I put

Both refer to string foo = "world";

 Console.WriteLine("Hello" + foo); //Concatenation 

and

 Console.WriteLine("Hello {0}", foo); //Whatever this is called (still a beginner guys)
rguarascia.ts
  • 694
  • 7
  • 19

4 Answers4

1

Concatenation simply puts two strings together. This is an extremely common practice found in just about every programming language.

Your second example is called string formatting. This gives you a lot of control of how the string will look when it's displayed, depending on what language or framework you're using.

Here's a great link to an explanation of string formatting. It uses string.Format() instead of the console but the concept still applies.

keeehlan
  • 7,874
  • 16
  • 56
  • 104
1

both look similar as you use string types. suppose you deal with different types. Then you will see the difference between Concatenation and Composite Formatting.

 int myInt = 2;
 Console.WriteLine("This is my int {0}", myInt);

Suppose now you want to put more types inside the composite formatting:

 char  myChar = 'c';
 bool myBool = true;

 Console.WriteLine("This is my bool {0} and myChar {1}", myBool ,myChar );

But Concatenation is the process of appending one string to the end of another string. When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs. However, string variables can be concatenated only at run time. In this case, you should understand the performance implications of the various approaches.

0

The second option allows you to do more complex formatting. With a string, there is little advantage, but if you were using a double value, for example, you could use the composite format options to specify the amount of precision to display or other options.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

This is a type of string formatting.

What Console.Write is doing is the equivalent of this:

String.Format("Hello {0}. I am {1} years old.", PersonName, PersonAge);

It just concatentates the string in an easier to understand way, as compared to:

"Hello " + PersonName + ". I am " + PersonAge + " years old.";
mnsr
  • 12,337
  • 4
  • 53
  • 79