String Concatenation and Operator Precedence

05 Feb
CodingOperators

String Concatenation and Operator Precedence

Ever wondered what the output of a seemingly straightforward piece of code might be, especially when it involves string concatenation and arithmetic operations? Consider the following C# examples:

Console.WriteLine("The value is: " + 11);
Console.WriteLine(3 + "º value");
Console.WriteLine("The value is: " + ( 3 + 1));
Console.WriteLine((3 + 18) + "º value");
Console.WriteLine("The value is: " + 2 + 4);
Console.WriteLine(5 + 6  + "º value");

This post aims not at debating best practices for string concatenation but at shedding light on operator precedence and its impact on our code's output.

When a string and a number are concatenated, the number is first converted to a string. Hence, the initial examples output:

The value is: 11
 value

For operations requiring prior calculation before concatenation, parentheses alter the operation order, leading to outputs like:

The value is: 4
21º value

However, the outputs of the last two lines might not be as intuitive:

The value is: 24
11º value

Let's delve deeper. The curiosity arises, especially with the expected output of 56º value for the last line, but instead, we get 11º value. This discrepancy stems from the operations' order.

In the fifth example, starting with a string prompts immediate concatenation: The value is: with 2 becomes The value is: 2, followed by another concatenation with 4, resulting in The value is: 24.

Conversely, the sixth line starts with two numbers, leading to their addition (5 + 6 = 11), followed by concatenating this result with º value, producing 11º value.

Conclusion:

Understanding operator precedence is crucial to predicting code outcomes accurately. The + operator, when applied between strings and numbers, results in concatenation. A behavior not unique to C# but shared across many languages like JavaScript, Java and so on.

We are using cookies to ensure that we give you the best experience on our website. By clicking "Accept", you consent to the use of ALL the cookies. However you may visit Cookie policy to provide a controlled consent.