Concatenating a Text and a Number

Except for addition of numbers, the operator + is used for joining a text (concatenation of two strings one after another). In programming, joining a text with a text is called "concatenation". Here is how we can concatenate a text with a number by the + operator:

var firstName = "Maria";
var lastName = "Ivanova";
var age = 19;
var str = firstName + " " + lastName + " @ " + age;
Console.WriteLine(str);  // Maria Ivanova @ 19

Here is another example:

var a = 1.5;
var b = 2.5;
var sum = "The sum is: " + a + b;
Console.WriteLine(sum);  // The sum is: 1.52.5

Did you notice something strange? May be you expecteded the numbers a and b to be summed? Actually the concatenation works from rigth to left and the result above is absolutely correct. If we want to sum the numbers, we have to use brackets, in order to change the order of execution of the operations:

var a = 1.5;
var b = 2.5;
var sum = "The sum is: " + (a + b);
Console.WriteLine(sum);  // The sum is: 4

results matching ""

    No results matching ""