11

Possible Duplicate:
c# convert char to int

This works:

int val = Convert.ToInt32("1");

But this doesn't:

int val = Convert.ToInt32('1'); // returns 49

Shouldn't this convert to actual int?

vent
  • 1,033
  • 10
  • 21

5 Answers5

18

It is returning the ASCII value of character 1

The first statement treats the argument as string and converts the value into Int, The second one treats the argument as char and returns its ascii value

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
2

The code '1' is the same as (char)49 (because the Unicode code point of the character 1 is 49). And Convert.ToInt32(char) returns the code point of that character as an int.

leppie
  • 115,091
  • 17
  • 196
  • 297
svick
  • 236,525
  • 50
  • 385
  • 514
2

As the others said, Convert returns the ASCII code. If you want to convert '1' to 1 (int) you should use

int val = Convert.ToInt32('1'.ToString());
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189
1

As others have already pointed out: In your second example ('1') you are using a char literal. A char is a numeric type. There is no parsing done as in the string example ("1"), since it already is a number - just a cast to a wider number format (from 16 bits to 32 bits).

Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
1

It treats '1' as char and int form of any char is its ASCII equivalent so it return its ASCII equivalent. But in case of "1" it treats it as string and convert it to integer.

Nakul Chaudhary
  • 25,572
  • 15
  • 44
  • 47