The other answers here haven't explained why you are seeing those unexpected numbers.
I think you are probably expecting the loop foreach (int item in numbers)
to loop through the individual "numbers" in the string and automatically cast these numbers to integers. That's not what's happening (well, it is, but not how you expect).
The foreach
loop is converting the string
to IEnumerable<char>
and iterating through each char
character in the string starting '3', '7', '1', ...
.
In .Net
characters and strings are encoded in unicode UTF-16 (as @TomBlodget pointed out in the comments). This means that each char
can be converted to it's character code unit. Your code will actually sum the character code units.
In C#
the code units for the characters '0', '1',..,'9'
is in the range 48,...,57. For this reason you can do something like @Yeldar's answer:
foreach (char item in numbers)
sum += item - '0'; // if item == '9' this is equivalent to 57 - 48 = 9
So, if the string only contains numbers then subtracting the '0'
character will implicitly convert the char
to it's int
counterpart and you will end up with the actual numerical value it represents (ie '7' - '0' => 55 - 48 = 7
).
The other answers here provide solutions to overcome the issue. I thought it would be useful explain why it was happening.