I’m just wondering why the compiler gives me this error. The try block will be executed every time the function is called and that means the variable will get assigned. But still it doesn’t let me compile.
using System;
namespace Checking
{
class Program
{
static void Main(string[] args)
{
int intNum;
intNum = readValue("Please enter a number: ");
}
static int readValue(string strPrompt)
{
int intRes;
Console.WriteLine(strPrompt);
try
{
intRes = Convert.ToInt32(Console.ReadLine()); // Gets assigned here! But still doesnt allow me to compile!
}
catch (Exception ex)
{
Console.WriteLine("Please enter a numeric value.\n");
readValue(strPrompt);
}
return intRes;
}
}
}
Putting return intRes inside the try block allows me to get rid of that error, but then an error crops up saying not all code paths return a value. I understand the errors, but I still don’t understand why it won’t allow me to compile, the try block gets executed every time right?
I also know that assigning 0 to intRes will get rid of that error.
Regards,
The compiler is right. The variable is not always assigned.
If the conversion fails, the assignment never happens, and the execution continues inside the catch block, where you call the function again, but you have forgotten to assign the return value of that call to the variable:
Here’s an anternative implementation using a
whileandTryParse: