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.
Use of unassigned local variable 'name' The C# compiler doesn't 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.
A local variable is defined (by an assignment) but never used. It is sometimes necessary to have a variable which is not used. These unused variables should have distinctive names, to make it clear to readers of the code that they are deliberately not used.
An unassigned variable in C is not "an unknown", though it is (as an adjective) unknown. It's uninitialized and thus equal to some value though it must be initialized first in order to be useful since only then do we know how to predict its behavior.
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-blockfinally
finally-block
- The definite assignment state of
v
at the beginning of try-block is the same as the definite assignment state ofv
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 ofv
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.
What if new CurrencyVO()
causes an exception in the catch
block? A-ha!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With