Recently I have been informed that it is possible to concatenate integers (and other types) to string and vice versa, i.e.
// x == "1234"
// y == "7890"
string x = "123" + 4;
string y = 7 + "890";
For some reason I didn't think this kind of thing was allowed, so I have always been using (since .NET 2) the form:
// x == "1234"
// y == "7890"
string x = "123" + 4.ToString();
string y = 7.ToString() + "890";
where the integers are converted to strings. Has the former version always been available, and I've missed it, or is it something that is new to C# 4 (which is what I am using now)?
To concatenate a String and some integer values, you need to use the + operator. Let's say the following is the string. String str = "Demo Text"; Now, we will concatenate integer values.
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.
1. Using to_string() function. The most commonly used approach to concatenate an integer to a string object in C++ is to call the std::to_string function, which can return the string representation of the specified integer.
This has always been there. The +
is equivalent to string.Concat()
if at least one of the operands is a string. string.Concat()
has an overload that takes an object
instance. Internally it will call the object's ToString()
method before concatenating.
Found the relevant section in the C# spec - section 7.7.4 Addition operator:
String concatenation:
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.
Of course, the best answer is to use some form of:
String.Format("{0},{1}", "123", 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With