C# Increment String Number

Question and answer

You have a number stored as a string in your C# program. How can you increment the number? Occasionally programmers make mistakes because of how the string.Concat method works with the plus operator.

Examples

Note

The string "1234" contains a number and we can parse it with int.Parse without an error. Next, we see the problematic (WRONG) statements. In the two WRONG statements, the number is converted to a string, and then another number is converted to a string and appended. This is because the plus operator compiles to a call to the method string.Concat. The numbers 1 and 2 are then converted to strings and passed to string.Concat. The result is not what you might want.

Program that increments strings containing numbers [C#]

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

Correct version. The CORRECT statements use the addition in an expression before calling ToString. This means that the plus operator is actually just an addition, and the results are what we expect (1235 and 1236).

Plus means different things

Programming tip

In the C# language, the plus operator can be overloaded. This means plus can have very different actions in a string expression or a numeric expression. Adding one to a string will simply append the string representation of the value 1 to the end of the string. Adding one to a number will increment it.

Operator Overloading

Summary

Operators can be confusing in some programs. To understand what the operator does, you must know the types of the operands (such as strings, chars, or ints). Finally, you can use parentheses around an expression before invoking ToString.

ToString Usage String Type
.NET