• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.
    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C# Question about context in code

ghoulishlearns

New Coder
Hello, I'm currently learning C# by reading 'Introduction to CSharp by Rob Miles. I'm still really new at it but I have come across a part where I don't really understand the concept.

1598960208733.png

I don't really understand how ("2.0"+3.0); turns into 2.03, I understand that it takes "2.0' literally, which is why it is not addition but why is it 2.03 instead of 2.30? An easy to understand explanation would be highly appreciated, thank you.
 

swift

Coder
Because of the type inference you end up just concatenating two strings. When you do that the 2nd string is just "tacked on" at the end.

Suppose you concatenate "a.b" and "c" - you wouldn't expect the output to be "a.c" but actually "a.bc". This is the same as what is happening here. Presumably c# casts the float 3.0 to the string "3". And since you have explicitly defined "2.0", the interpreter does not need to make the type cast so it remains "2.0". Which results in havng the concatenation of the strings "2.0" and "3", giving you your "2.03" as a result.

Hope that helps a bit.
 

Trilient

New Coder
Because of the type inference you end up just concatenating two strings. When you do that the 2nd string is just "tacked on" at the end.

Suppose you concatenate "a.b" and "c" - you wouldn't expect the output to be "a.c" but actually "a.bc". This is the same as what is happening here. Presumably c# casts the float 3.0 to the string "3". And since you have explicitly defined "2.0", the interpreter does not need to make the type cast so it remains "2.0". Which results in havng the concatenation of the strings "2.0" and "3", giving you your "2.03" as a result.

Hope that helps a bit.
Just to add to this, in case it isn't clear the reason "3" is added to the end of the string and not "3.0" is due to the numeric value of "3.0" literally just being 3. So it's interpreted and added as such.
 
Top Bottom