Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Convert.ToInt32('1') returns 49? [duplicate]

Tags:

c#

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?

like image 581
vent Avatar asked Sep 08 '10 08:09

vent


People also ask

What does convert ToInt32 do in C#?

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.

Which is better int parse or convert ToInt32?

Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.

What is the difference between convert ToInt32 and convert toint64?

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).

Which statement accurately describes the difference between Int32 TryParse () and convert ToInt32 ()?

Parse() and Int32. TryParse() can only convert strings. Convert. ToInt32() can take any class that implements IConvertible .


2 Answers

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

like image 184
Sachin Shanbhag Avatar answered Oct 14 '22 01:10

Sachin Shanbhag


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());
like image 28
Jürgen Steinblock Avatar answered Oct 14 '22 02:10

Jürgen Steinblock