C# Increment String Number

Increment string number. Numbers are sometimes stored as strings. How can we increment these numbers? Occasionally programmers make mistakes because of how the string.Concat method works with the plus operator.

Example. The string "1234" contains a number. We can parse it with int.Parse. Next, we see problematic statements. In the two WRONG statements, the number is converted to a string, and then another number is converted to a string and appended.

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.

Based on:

.NET 4.5

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


	value2 = (number + 1).ToString(); // CORRECT
	value3 = (number + 2).ToString(); // CORRECT




Correct: 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).

Plus. In the C# language, the plus operator can be overloaded. Plus can mean different actions in a string expression or a numeric one. Adding one to a string will append the string representation of the value 1.

And: Adding one to a number will increment it. With the plus operator, context is important.


Summary. Operators are sometimes confusing. To understand an operator does, we must know the types of the operands (such as strings, chars, or ints). We can use parentheses around an expression before invoking ToString.