Concatenating integers to string in C#
This article illustrates the different techniques to concatenate integers to a string in C#.
Since the string is immutable in C#, you can’t append any characters to it. However, you can create a new instance of the string with desired characters appended to it. This post provides an overview of few available alternatives to accomplish this.
1. Using + operator
A simple solution to concatenate an integer to a string is using the + operator. The following sample illustrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "$"; int i = 100; s = s + i; Console.WriteLine(s); // $100 } } |
2. Using string.Concat() method
The String class provides an overload of the Concat() method that accepts an object. A call to the + operator translates to the string.Concat() method, when at-least one operand is a string. You can directly invoke the string.Concat() method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "$"; int i = 100; s = string.Concat(s, i); Console.WriteLine(s); // $100 } } |
3. Using string.Format() method
You can also use the string.Format() method to insert a value into a string. The following code example demonstrates how to invoke the String.Format() method to concatenate an integer to a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "$"; int i = 100; s = string.Format("{0}{1}", s, i); Console.WriteLine(s); // $100 } } |
That’s all about concatenating integers to string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)