I can't use the variable assigned in the Try {} scope in the main scope, but after adding a return to catch {}, can I?

I am trying to understand why this code is able to use a variable from the validation scope. If I hadn't implemented the return to catch {} it would throw an error, but with the return in catch everything would work without issue, I really don't understand why, I expect both of them to throw an error. So why can it work?

static void Main(string[] args)
    {
        DayOfWeek favDay;
        try
        {
            favDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), Console.ReadLine());
        }
        catch(Exception x)
        {
            Console.WriteLine(x.Message);
            Console.ReadLine();
            return; // Without implementing this return I cannot use variable favDay after in Main to pass it into Method.
        }
        Print(favDay);
        Console.ReadLine();
    }

static void Print(DayOfWeek x)
    {
        switch (x)
        {
            case DayOfWeek.Friday:
                Console.WriteLine("Weieeeee");
                break;
            default:
                Console.WriteLine(":(");
                break;
        }
    }

      

Thanks for your reply.:)

+3


source to share


2 answers


By adding a statement return;

, you prevent the method from accessing the use of the variable favDay

, unless it has been assigned. The only other code path that would lead to being used at the end of the method is through a successful assignment in the block try

, so the variable is assigned before later use.



Without a statement, return;

you will get an "unassigned local variable use" error because execution might reach the block catch

before assigning a variable in the block try

, and then jump to using the variable without assigning a value to the variable.

+3


source


The reason for the action you see is that the variable was not initialized and returned; in catch automatically outputs a null value to initialize the variable needed to use the variable for other functions. So the method would be a mistake in this case to keep any exception from going forward.



0


source







All Articles