Why does this C# code throw an error: Use of unassigned local variable 'n'

前端 未结 4 538
我在风中等你
我在风中等你 2021-01-21 05:26

On MSDN, this code is posted at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch I am unable to understand why it throws the error:

4条回答
  •  面向向阳花
    2021-01-21 05:53

    I believe, what you're confused about, is that even though the variable n appears to be initialized, why the compiler complains it isn't?

    And there's a good reason for that; even though n is initialized at one point, it isn't initialized in all possible paths. In other words, you have to account for each scenario in your code and ensure that in all of them, the initialization occurs.

    But in this case, it doesn't satisfy that condition. In your try block, if there was an exception before the program gets to execute the n = 123; line, the program will go to the catch and then following that, will go to your Console.Write(n) line at which point you're trying to print a variable that isn't initialized.

    So, the best way to prevent such a scenario is to initialize the variable before the try block. In general it is advised that you always initialize a variable as soon as it is declared.


    EDIT

    From a beginner's point of view, you might argue that there's only one line of code inside the try block, and therefore there's no way the program will not execute the initialization. But you must look at it from the compiler's perspective; it doesn't understand the intention of your program, it simply verifies (that's what a compiler does) if a program is written according to a predefined set of rules. And in this case, it isn't.

提交回复
热议问题