简体   繁体   中英

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

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:

Use of unassigned local variable 'n'.

static void Main()   
{  
    int n;  

    try   
    {  
        // Do not initialize this variable here.  
        n = 123;  
    }  
    catch  
    {  
    }  

    // Error: Use of unassigned local variable 'n'.  
    Console.Write(n);  
}

Compiler Error CS0165

The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. For more information, see Fields . Note that this error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not . This avoids the necessity of overly-complex rules for definite assignment.

More-so , imagine this situation

int n;  

try   
{  
    throw new Exception();
    n = 123;  // this code is never reached
}  
catch  
{  
}  

// oh noez!!! bam!
// The compiler is trying to be nice to you 
if(n == 234);

In short, computer says no

Note : when you get a compiler error in visual studio, you can click on the error code and it sometimes (if you are lucky) gives you more concise information about what the error means

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.

If you look at the article, you'll see the answer:

// Error: Use of unassigned local variable 'n'.

When you write int n; you do not initialize variable and try to use it in Console.Write(n); , so you will get compilation error: https://ideone.com/q3LXwl

This error is because you are using n in Console.Write() function. And suppose if Try block generates an exception then n would not be initialized. Therefore this error occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM