473,320 Members | 2,006 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 13590
"Elena" <El***@discussions.microsoft.comha scritto nel messaggio
news:9E**********************************@microsof t.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(string, int) the called overload is
string.Concat(object, 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(string, int) the called overload is
string.Concat(object, 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.OutOfMemoryException
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***@removethis.dystopia.fi
http://www.saunalahti.fi/janij/
Dec 16 '06 #4

"Jani Järvinen [MVP]" <ja***@removethis.dystopia.fiha scritto nel
messaggio news:ul**************@TK2MSFTNGP03.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.OutOfMemoryException 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.googlegro ups.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.ToString()) + 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**********************************@developm entnow.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
Thanks for the responses. The conversation was interesting. My queasiness
about the implicit conversion is that it was not predictable (by me) - one
really has to know the conventions.
Dec 18 '06 #11

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

Similar topics

5
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...
3
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,...
81
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...
11
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 =...
10
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...
1
by: manchin2 | last post by:
Hi, Can anybody please provide the information about "&quot" and its use, if possible please provide an example. ...
29
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...
4
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...
8
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.