Search code examples
c#try-catchunassigned-variable

Use of unassigned local variable. But always falls into assignment


having this code, I don't understand why if assigning a variable in a finally block doesn't understand it will ALWAYS be assigned. I think I missing a valid option where currency won't be assigned. If you know, will be great to understand why. much appreciate it!

Thanks!

CurrencyVO currency;

try
{
     if (idConnection.HasValue && idConnection != 0)
     {
         currencyConnection = client.GetConnection(idConnection.Value);
         model.Connection = currencyConnection;
     }
     else 
     {
         int providerUserKey = (int)Models.UserModel.GetUser().ProviderUserKey;
         currencyConnection = client.GetConnection(providerUserKey);
     }                        
     currency = model.Currencies.SingleOrDefault(c => c.IdCountry == currencyConnection.idcountry) ?? new CurrencyVO();    
} 
catch
{
      currency = new CurrencyVO();                    
} 
finally
{
      model.PublishedContainer.Currency = currency;
}

the error happens on the finally block. If i take it out of the finally block like this :

                } catch {
                    currency = new CurrencyVO();
                }
                model.PublishedContainer.Currency = currency;

it works fine.


Solution

  • The definite assignment tracking that the C# compiler performs doesn't necessarily perform a complete analysis (that wouldn't be possible in the general case) - there are rules that restrict how complex of an analysis the compiler will perform. The rule covering the finally block here is documented at http://msdn.microsoft.com/en-us/library/aa691181.aspx:

    For a try statement stmt of the form:

    try try-block finally finally-block

    • The definite assignment state of v at the beginning of try-block is the same as the definite assignment state of v at the beginning of stmt.
    • The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.
    • ...

    So for your particular example, since currency is not definitely assigned at the beginning of the try block, it is considered to be not definitely assigned at the beginning of the finally block.