473,666 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String "+" operator conversion

I am surprised to discover that c# automatically converts an integer to a
string when concatenating with the "+" operator. I thought c# was supposed
to be very strict about types. Doesn't it seem like c# is breaking its own
rules?

This works:
int b = 32;
string a = "ABC " + b;

Result: a = "ABC 32"

but this line will cause an error:
a = b;

Dec 16 '06 #1
10 13628
"Elena" <El***@discussi ons.microsoft.c omha scritto nel messaggio
news:9E******** *************** ***********@mic rosoft.com...
>I am surprised to discover that c# automatically converts an integer to a
string when concatenating with the "+" operator. I thought c# was
supposed
to be very strict about types. Doesn't it seem like c# is breaking its
own
rules?

This works:
int b = 32;
string a = "ABC " + b;

Result: a = "ABC 32"

but this line will cause an error:
a = b;
mmm... I took a look to the IL produced.
C# compiler to concatenate strings call string.Concat() .
Since there is not string.Concat(s tring, int) the called overload is
string.Concat(o bject, object).
If you look inside it (I used Reflector) you can see

return (arg0.ToString( ) + arg1.ToString() );

So this is the discovered secret :)

Dec 16 '06 #2
Fabio,

The thing is why the compiler decide so.
Sure that it is not string concatenation if "1 + 1" or "new Object() +
1".
If one or more operands are string, it is string concatenation.
This is true for both C# and Java.

Thi
http://thith.blogspot.com

Fabio wrote:
C# compiler to concatenate strings call string.Concat() .
Since there is not string.Concat(s tring, int) the called overload is
string.Concat(o bject, object).
If you look inside it (I used Reflector) you can see

return (arg0.ToString( ) + arg1.ToString() );

So this is the discovered secret :)
Dec 16 '06 #3
Hello!
If one or more operands are string, it is string concatenation.
Correct. This behavior is also specified in the C# language specification.

From the C# Language Specification 1.2, §7.7.4, Addition operator:

----------------
"String concatenation: 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. [...] A System.OutOfMem oryException
may be thrown if there is not enough memory available to allocate the
resulting string."
----------------

The specification is available here:

http://msdn2.microsoft.com/en-us/library/ms228593.aspx

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
ja***@removethi s.dystopia.fi
http://www.saunalahti.fi/janij/
Dec 16 '06 #4

"Jani Järvinen [MVP]" <ja***@removeth is.dystopia.fih a scritto nel
messaggio news:ul******** ******@TK2MSFTN GP03.phx.gbl...
>If one or more operands are string, it is string concatenation.
And I sayd why :)
Correct. This behavior is also specified in the C# language specification.

From the C# Language Specification 1.2, §7.7.4, Addition operator:

----------------
"String concatenation: 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. [...] A
System.OutOfMem oryException may be thrown if there is not enough memory
available to allocate the resulting string."
----------------
This is a bit deceptive, since the IL produced *dont't* checks for any null
operand, but the string.Combine( ) do it for the compiler.
Dec 16 '06 #5
Hi

when a string and int participate in + operation, that would be treated
as binary concatination between the strings. As the second argument is
int it would be pramoted to string by applying .ToString().

Yes , assigning is not possible because one is string and other is int.
C# is strict about types. that is the reason why it is promoted to
String while performing + and assigning... try running the following
code snippet, you will get to know about internal conversions and
strictness of C# on types.

int a = 32;
int b = 10;

string p = "ABC " + b;
string q = a + b;
string r = a + b.ToString();

Thanks
-Srinivas.

Elena wrote:
I am surprised to discover that c# automatically converts an integer to a
string when concatenating with the "+" operator. I thought c# was supposed
to be very strict about types. Doesn't it seem like c# is breaking its own
rules?

This works:
int b = 32;
string a = "ABC " + b;

Result: a = "ABC 32"

but this line will cause an error:
a = b;
Dec 16 '06 #6
"Jani Järvinen [MVP]" wrote:
From the C# Language Specification 1.2, §7.7.4, Addition operator:

----------------
"String concatenation: 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.
Wow. Learn something every day.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Dec 16 '06 #7

"Duggi" <Du************ ***@gmail.comha scritto nel messaggio
news:11******** **************@ 79g2000cws.goog legroups.com...
Hi

when a string and int participate in + operation, that would be treated
as binary concatination between the strings. As the second argument is
int it would be pramoted to string by applying .ToString().

Yes , assigning is not possible because one is string and other is int.
C# is strict about types. that is the reason why it is promoted to
String while performing + and assigning...
I insist :)
the IL generated does not say that.
the compiler DOESN'T checks NOR promotes a thing.

Other thing is saying that the result is as the compiler does this and that.
;)
Dec 16 '06 #8
Actually that is expected what you are doing is an implicit conversion.

because every object has a base ToString() method when you are adding

"ABC" + b the compiler sees the left side of the assignment operator is a string and it uses what it has at its disposal to try and make all the values on the right side the same type. and since every object has at least 1 ToString() method it will always work.

it's the same thing as doing the following

int a = 10
long b = 98948989

long c = a + b

since the comiler is looking for a long to be assigned to c it implys that a needs to be converted to long which is why it's called implicit conversion

however the following will give you a comiler error

long a = 10009994
int b = 20

int c = a + b

the compiler can not implicitly convert from a larger type down to a smaller type to make this work you need an explicit conversion like the following

int c = int.Parse(a.ToS tring()) + b

we force the compiler to first convert the long to a string, then parse that string to turn it into an integer) now we can add them all together.

i would recomend you read up on implicit and explicit conversions in the .NET framework, they are very powerful and most often overlooked.

a few common points to remember

1. with EXPLICIT conversions you get out exactly what you tell the compiler to give
you nothing more nothing less

2. with IMPLICIT conversions you get out what the compiler thinks you need.

3. with IMPLICIT conversion the compiler will convert from smaller to larger

a. int -long
b byte -int
c. long -string
d. etc.....

4. with IMPLICIT conversion the compiler will give you an error if you try to let it try
and convert from a larger down to a smaller type

a. long -short
b. string -double
c. string -char
hope that helps clear up some confusion

From http://www.developmentnow.com/g/36_2...conversion.htm

Posted via DevelopmentNow. com Groups
http://www.developmentnow.com
Dec 17 '06 #9
"Ryan" <To*****@gmail. comha scritto nel messaggio
news:4b******** *************** ***********@dev elopmentnow.com ...
Actually that is expected what you are doing is an implicit conversion.
Good post.
It's a problem if NO implicit conversion are made in this case? :)

Please, read my first post.

The IL produced is:

L_0001: ldc.i4.s 32
L_0003: stloc.0 L_0004: ldstr "ABC "
L_0009: ldloc.0
L_000a: box int32
L_000f: call string string::Concat( object, object)
L_0014: stloc.1
L_0015: ret

So, please, let's stop to talk about implicit conversion or soft-type
checking.
Dec 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2926
by: Quentin Crain | last post by:
Hello All! Could someone explain (links are good too!) why: >>> 1+"1" Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unsupported operand types for +: 'int' and 'str' >>> 1=="1"
3
2414
by: beta | last post by:
Hello everyone, I need some help here. If anyone has encountered this, knidly give me your advice. I have a command button (Command0) and a listbox (List1). Upon clicking the command button, I want my listbox to be populated. Please look at the code below. The fields Day2 and Filename are both text fields. My problem is that Day2 field has rows with the text value "N/A" (without the quotes). MS Access is evaluating the "/" sign in
81
7295
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
11
1790
by: .Net Sports | last post by:
I need to convert some C# ?Conditionals over to vb.net (most likely in vb.net using If..Then statements), but the C#2VBNETconverter by KamalPatel isn't converting them: string PurchaseType = (Convert.ToString(drwData) == "True") ? "ID" : "PID"; XmlNodeList Selections = xdcData.GetElementsByTagName((X == 0) ? "Highlight" : "Selection");
10
9054
by: lovecreatesbea... | last post by:
Is it correct and safe to compare a string object with "", a pair of quotation marks quoted empty string?If the string object: s = ""; does s contain a single '\'? Is it better to use std::string::size or std::string::empty to deal with this condition? Thank you. string s = ""; if (s == ""); if (s.size == 0); if (s.empty());
1
2836
by: manchin2 | last post by:
Hi, Can anybody please provide the information about "&quot" and its use, if possible please provide an example. 1)<tm:bom-expression>{Conf.getEquityConfLookupFields().getEventFieldText(&quot;AdditionalDisruption&quot;,&quot;Change in Law&quot;)}</tm:bom-expression> 2)07:41:08 Default ( call ( . ( call ( . Conf getEquityConfLookupFields ) ) getEventFieldText ) ( , AdditionalDisruption Change inLaw ) ) value=Not applicable Can you please...
29
2415
by: Java script Dude | last post by:
Greetings, Now I can understand that 0 equal false, but should "" also equal false? Apparently the answer is yes. When I test both Firefox and IE, they both say ""==false . I assume this goes back to the original spec for JavaScript. Not very intuitive but I guess I can code around this.
4
3883
by: fran7 | last post by:
Hi, from help in the javascript forum I found the error in some code but need help. This bit of code works perfectly, trouble is I am writing it to a javascript function so the height needs to be in &quot;&quot; instead of "" otherwise I get an error message. Can anyone suggest how to write it so that it writes &quot; instead of "". I have tried all combinations of adding &quot; to the code but as soon as I think I am there I get throw out again. if...
8
1989
by: vtuning | last post by:
Hi, i'm doing a project in Visual C++....in Portuguese....i'm hoping you can help figure out the problem eventhough it's not in english... here is the whole code....incomplete in the int main and it's missing some functions but i wanted to solve this errors before i keep going Class.h class CNoFila{ public: int evento; int tempo; int numcliente;
0
8878
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8785
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8560
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8644
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7389
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1778
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.