Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why cannot I make the variable 'choice' as int type in this ? I tried making choice as int type but it gave the error that I cannot convert string to int implicitly.

C#
Console.WriteLine("Enter a choice");
string choice;
choice = Console.ReadLine();
Console.WriteLine("you have entered:" + choice);
Console.ReadLine();
Posted
Updated 21-Feb-13 1:43am
v2

Console.ReadLine[^] returns a string, so you cannot use it to read an integer. You need to use one of the Int32[^] Parse methods to convert the string.
 
Share this answer
 
Console.ReadLine()
return type is string so choice must be string, but if you want to declare choice as int than follow the code below

C#
Console.WriteLine("Enter a choice");
int choice;
if (int.TryParse(Console.ReadLine(), out choice))
{
    Console.WriteLine("you have entered:" + choice);
}
else
{
    Console.WriteLine("you have entered non numberic number" );
}
Console.ReadLine();
 
Share this answer
 
Hii professional

ya Richard is right........
there is no any error with choice.
the main fault is that you want to read int data type to string directly without any conversion that's why "cannot convert string to int implicitly" is coming...

for more knowledge read this link.........

http://www.dotnetperls.com/int-parse[^]

Happy to help...
 
Share this answer
 
Comments
Shubh Agrahari 21-Feb-13 9:36am    
what is problem that need to down vote.....really embarrassing.........
Richard MacCutchan 21-Feb-13 9:53am    
Probably because your answer is not clear, and you have really not done much more than repeat the information in my response.
Shubh Agrahari 22-Feb-13 3:55am    
ok i am getting that what actually you want to share with me.......but sorry i am not agree with you that i am repeating your words because if there need to parse method for string , int to string(because Console.readLine does not direct accept int value) then there is no way do define it with any else answer..my friend i am not taking your credential just to appreciate you.

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