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?
ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
Thus int32 would be limited to a value between (-256^4/2) and (256^4/2-1). And int64 would be limited to a value between (-256^8/2) and (256^8/2-1).
Parse() and Int32. TryParse() can only convert strings. Convert. ToInt32() can take any class that implements IConvertible .
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With