HomeSearch

C# Increment String That Contains a Number

This C# article considers an issue with incrementing numbers stored as strings. It uses int.Parse and ToString.
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.

string.Concat

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

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
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.

Operator
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.ToString
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls