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.
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
finallyblock here is documented at http://msdn.microsoft.com/en-us/library/aa691181.aspx:So for your particular example, since
currencyis not definitely assigned at the beginning of thetryblock, it is considered to be not definitely assigned at the beginning of thefinallyblock.