December 2nd, 2011, 06:02 PM
Re: Cannot implicitly convert type "string" to "int"
Aah, I missed that bit.
Look what u have:
Line 01 declares the guess to be an integer.
01: int guess;
02: int.TryParse(Console.ReadLine(), out guess);
// then later, in do-while:
03: guess = Console.ReadLine();
Line 02 is equivalent to:
ReadLine returns a string, and try parse expects a string as its first parameter (this is the string you want to parse and convert to an integer). This is why, instead of the temp variable used here, you can put in the ReadLine() call directly - the method returns a string, and this result is passed as the parameter. Guess is passed by reference via the out keyword, which enables the TryParse() method to change the value of the variable internally, in a way that affects your original guess variable (that is, the method doesn't make it's own copy).
string temp = Console.ReadLine();
int.TryParse(temp, out guess);
When TryParse() is done, guess will contain the appropriate value.
All that means that line 03 is completely redundant, aside from the fact that it won't compile. You can safely delete it. Again, the reason the compiler complains is because ReadLine() returns a string, but the guess variable now accepts only integers, as you yourself have declared in line 01.
Tags for this Thread
Click Here to Expand Forum to Full Width