Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Basics (Retired) Perform Integers

What Logic is C# Using that "Helping Us Out" Ends in Converting an Int into a String when Adding a String and an Int?

string myString = 5;
int myInt = 8;
myString + myInt

//Result is "58", which is "incorrect" for our purposes in this exercise, the answer "should be" 13

Jeremy mentions that C# is trying to "help us out" by converting the int variable that we're adding to a string variable into a string, so C#'s REPL ends up concatenating the 2 numbers into a string, resulting in "58".

I'm not understanding how the C# REPL determines to convert both the string and the int variables into strings...wouldn't converting them both to ints be equally as likely? Why or why not? I just don't understand the logic happening underneath the surface, which is the result "58" as a concatenated string.

2 Answers

Hi

This is not a C#'s REPL this. It is how the C# compiler works.

Basically, the rules for expression evaluation is:

if one operand of the + operator is a string and the other isn't, then the one that isn't is converted to string using the built in toString() method

then and only then, all the operands are concatenated left to right.

Hope this helps. If this answers your question, please mark the question as answered.

Thanks

Avan Sharma
Avan Sharma
7,652 Points

Honestly, you would not understand the logic because this '+' is doing some overloaded operation. If there are two integers it adds them like mathematics stuff.

If they are "strings" it concatenates them . If you pass a string + int , then implicitly compiler parses the integer to string and append it to the end of the string. Thus "5" + 8 becomes 58. Implicitly happening behind the scene.

Why they turn into strings is probably because of Object.ToString() method is called on the integer object. This is all happening under the hood implicitly .