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

前端 未结 4 539
我在风中等你
我在风中等你 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:52

    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

提交回复
热议问题