Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding integers to strings in C# [duplicate]

Tags:

c#

c#-4.0

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

like image 797
A.R. Avatar asked Feb 23 '12 18:02

A.R.


People also ask

Can we add integer with string?

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.

How do you add integers and strings?

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.

Can you add characters to a string in C?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.

How do I concatenate a number to a string in C++?

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.


2 Answers

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.

like image 73
BrokenGlass Avatar answered Oct 12 '22 20:10

BrokenGlass


Of course, the best answer is to use some form of:

String.Format("{0},{1}", "123", 4);
like image 20
Joe Avatar answered Oct 12 '22 19:10

Joe