C# Error variable is unassigned in try catch method?

static void Main(string[] args)
    int lengthCountdown;
    print tell = new print();
    timer counter = new timer();
    Error invalidInput = new Error();
    tell.tell("Hi i am John");
    tell.tell("How long should the countdown last?");
        lengthCountdown = int.Parse(Console.ReadLine());
    tell.tell("That was a " + lengthCountdown + " second countdown");

It says that there is an Error at "lengthCountdown" in counter.timing. Error: "Use of unassigned local variable"... If I am not using the try-catch method it isn't showing the Error.

Jon Skeet

If you don't have the try/catch block, you'd only ever reach the statement that uses lengthCountdown if the assignment had succeeded anyway.

If int.Parse or Console.ReadLine() throw a FormatException, you're currently catching that exception and then proceeding, despite the fact that no value will have been assigned to the lengthCountdown variable. The compiler is stopping you from trying to read the value of the variable without it having been assigned a value in your code.

It's not clear what you want to do when there's an error in user input, but proceeding with the rest of the code as if you have valid information (even after warning the user, or whatever invalidInput.valueError() does) is a bad idea. You could just give lengthCountDown an initial value at the point of declaration, but that's unlikely to be wise in this case.


See more on this question at Stackoverflow