Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Why is Use of an unassigned local variable allowed here?

Normally the compiler forbids any use of unassigned local variables, but not in the following case. Why?

private void Main()
{
    // This local variable is unassigned.
    string myVar;
    
    try
    {
        // The Throw() method prevents the assignment from happening...
        myVar = Throw();
    }
    finally
    {
        // ... so myVar is still unassigned.
    }

    // Here we use myVar, which is unassigned, and the compiler is not complaining.
    if (myVar.Equals("Something"))
    {
        // ...
    }
}

private string Throw()
{
    throw new Exception();
} 
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The exception in the example is not caught by Main(). Therefore, if the exception is thrown, the code after the finally block is unreachable, and if the exception is not thrown, the assignment occurs. That's why in any case a use of an unassigned variable cannot happen. And since it cannot happen, the compiler doesn't report it.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!