CSharp - What is the output: Mix number calculation with text?


What is the output of the following code?

using System;

class Program{
    static void Main(string[] args){
        Console.WriteLine("a) " + 1 + 1);
        Console.WriteLine("b) " + (1 + 1));

Click to view the answer

a) 11
b) 2


When you mix numbers with text, the result might appear different.

for a). The computer calculates the whole expression from left to right.

First, it takes the text a) and a number (the first 1).

It joins them together to be 'a) 1'.

Then, it takes this new text and the final number (the second 1) and again joins them together to obtain the text a) 11.

In (b). The parentheses make the computer perform the addition of the numbers first, joining the text on the left only afterward.