Why can't I assign object variables within the try
block?
If I attempt to do this and clean up the variable in the finally
block I get a compiler error: "use of unassigned local variable". This makes no sense because the variable is declared before the try
block, and in the finally
block I am first checking whether the variable is null
.
Why can't the following code compile? I am checking whether dbc
is null
so there's no chance of it trying to do something with an unassigned variable.
eg:
DbConnection dbc;
try {
dbc = <some method call returning an open DbConnection>
// do stuff
} catch (Exception e) { // do stuff }
finally {
if (dbc != null) {
dbc.Close();
}
}
Change your declaration to DbConnection dbc = null;
so the compiler can know for certain that the variable is assigned. (Merely declaring dbc
is not the same as assigning it a value of null, you must be explicit with a local.)
The reason your existing code fails is that it is entirely possible for an exception to occur before dbc is set. As such, the compiler cannot assume that dbc is assigned by the time the finally block executes.
For more info, see section 5.3 of the language specification on definite assignment.
http://msdn.microsoft.com/en-us/library/aa691172(VS.71).aspx