3

I just collected some knowledge regarding and it seems to be very little to understand following scenario.

I have 2 classes. One has Main method and other has two Extension Methods as follow.

Class having Main

class Program { static void Main(string[] args) { string uuu = "214"; Console.WriteLine(uuu.SplitMe().AddMe()); Console.ReadKey(); } } 

Extension Class

static class ExtensionClass { public static char[] SplitMe(this string value) { return value.ToCharArray(); } public static long AddMe(this char[] value) { int sum = 0; for (int i = 0; i<value.Length ; i++) { sum += Convert.ToInt32(value[i]); } return sum; } } 

I was expecting, in following line

Console.WriteLine(uuu.SplitMe().AddMe()); 

output of uuu.SplitMe() to be char[] of {'2','1','4'} and result of complete line to be printed as 7 (2+1+4) but it is 151 on my console. Could you please elaborate how its being calculated?

Thanks.

5
  • 4
    this has nothing to do with extension methods Commented May 26, 2014 at 18:18
  • Use Int32.Parse instead Commented May 26, 2014 at 18:20
  • '2' is has not the value of 2. If you convert '2' to a number, you will get the ACII code for the letter '2'. If you want to parse a number use Int32.Parse. Commented May 26, 2014 at 18:26
  • @thefiloe .NET generally uses the Unicode character set and the UTF-16 and UTF-8 encodings. You can only get ASCII codes if you explicitly use ASCII conversion methods (or depend on their numerical equivalence but that leads to errors with characters not supported by ASCII). Commented May 26, 2014 at 21:18
  • If you do something like (int)'2' you will get the ACII code. Commented May 27, 2014 at 9:15

4 Answers 4

8

The issue is that a System.Char value of '2' has an integer value of 50, not 2. As such, you're summing {'2','1','4'}, which have values of {50, 49, 52}, which in turn becomes 151.

You could convert the characters to numbers matching their value via:

sum += int.Parse(value[i].ToString()); 

However, this will raise an exception if you pass a string that contains non-numeric characters.

Sign up to request clarification or add additional context in comments.

Comments

1

The value of a char containing 2 is not 2, but 50, as its position in the ASCII table is used as its value; the same goes for the other numbers, which explains the unexpected result.

Comments

0

Convert.ToInt32 does not convert the numeric string value, but the specified Unicode character to the equivalent 32-bit signed integer.

Comments

0

Because the ascii value of 2 is 50 1 is 49 and 4 is 52. so it is adding those values..

you need to change your code

public static long AddMe(this char[] value) { int sum = 0; for (int i = 0; i < value.Length; i++) { sum += value[i]-48; } return sum; }

or you can do this also

sum += int.Parse(value[i].ToString()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.