Click here to Skip to main content
15,890,717 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi, Look at the Following code
C#
char c = 'a';
a=Convert.ToInt32(c);
Console.WriteLine("hi" + a);//displays output:- Hi97
a=Convert.ToInt32(Console.ReadLine());//Gives complie time error(throws an exception) if I enter 'a'(a only without quotes) on screen.

Why the Convert.ToInt32() is behaving differently in 2 situations.
Posted
Updated 6-Dec-11 6:06am
v2

In the first case you have defined a single character which is converted to ascii value (97) when added to the string.

When you use Console.ReadLine() method, the method doesn't return a character but a string. So this string cannot be converted to integer if it contains characters.
 
Share this answer
 
See the documentation[^] for this and other situations.
 
Share this answer
 
Because the equivalent of 'a' in ASCII character set is 97. Using Int32.TryParse method would be better in this case. See the link for your reference:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx[^]

Regards,
Eduard
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900