Home
C#
Increment String, Number
Updated Sep 26, 2022
Dot Net Perls
Increment string, number. Numbers are sometimes stored as strings. How can we increment these numbers? We must convert the strings to numbers to increment them.
String concatenation is not the same thing as incrementing a number. Occasionally programmers make mistakes because of how the string.Concat method works with the plus operator.
Example. We can parse the string "1234" with int.Parse. 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
Detail 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).
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); } }
12341 12342 1235 1236
Plus operator. In the C# language, the plus operator can be overloaded. Plus can mean different actions in a string expression or a numeric one.
So Adding one to a string will append the string representation of the value 1. Meanwhile adding one to a number will increment it.
operator
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
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen