'C# does not recognize a variable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school_project_final
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("who are you...?");
            
            string name = Console.ReadLine();

            Console.WriteLine("how old are you " + name + "?");

            int age;

            try
            {
                age = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("that's... not a number");
                return; 
            }
            finally
            {
                if (System.Convert.ToInt32(age) >= 18)
                {
                    Console.WriteLine("so you're " + age + " years old, good to know");
                }
                else if (System.Convert.ToInt32(age) < 18 && System.Convert.ToInt32(age) > 0)
                {
                    Console.WriteLine("so you're a child, how worthless");
                }

                Console.ReadLine();
            }
        }
    }
}

if (System.Convert.ToInt32(age) >= 18)

This line returns an error that the age variable does not exist, but the other lines after it like

Console.WriteLine("so you're " + age + " years old, good to know");

and

else if (System.Convert.ToInt32(age) < 18 && 
         System.Convert.ToInt32(age) > 0)

do not return this error, how do I fix this?



Solution 1:[1]

finally always runs after try/catch, even if there's an execption That's why compiler doesn't think there's a value for age

Add your if/else statements in try block

try
{
    age = Convert.ToInt32(Console.ReadLine());
    
    if (age >= 18) 
    {
        Console.WriteLine("so you're " + age + " years old, good to know");
    } 
    else if (age < 18 && age > 0) 
    {
        Console.WriteLine("so you're a child, how worthless");
    }

    Console.ReadLine();
}
catch (FormatException)
{
     Console.WriteLine("that's... not a number");
     return; 
}

Solution 2:[2]

The compiler thinks the age value is not assigned in the finally block because it's scope is evaluated regardless of the try block successfully running. In other words, if you got an exception, the finally block wouldn't have any value of age unless you assigned it to something else in the catch.

Your if/else statements should be in the try block

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Almost
Solution 2 OneCricketeer