Why does this C# code throw an error? [on hold]

  • A+

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 an error.

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: