Search code examples
c#console.writeline

Difference between concatenation and {}


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)

Solution

  • 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.