Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • 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.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • 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.
 
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.
 
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.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom