C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This is because the plus operator compiles to a call to the method string.Concat.
Then: The numbers 1 and 2 are converted to strings and passed to string.Concat.
string.ConcatCorrect: The CORRECT statements use addition in an expression before calling ToString.
And: The plus operator is just an addition. The results make sense (1235 and 1236).
C# program that increments strings containing numbers
using System;
class Program
{
static void Main()
{
string value = "1234";
int number = int.Parse(value);
string value2 = number.ToString() + 1; // WRONG
string value3 = number.ToString() + 2; // WRONG
Console.WriteLine(value2);
Console.WriteLine(value3);
value2 = (number + 1).ToString(); // CORRECT
value3 = (number + 2).ToString(); // CORRECT
Console.WriteLine(value2);
Console.WriteLine(value3);
}
}
Output
12341
12342
1235
1236
And: Adding one to a number will increment it. With the plus operator, context is important.
Operator