Consider allowing finally block to access variables declared in try block. #2213
-
In code where we declare values outside of a try/catch/finally we can access those variables within the catch/finally. This suggestion is to adjust the implementation of this area so that catch/finally can also access variables declared within the try. This would be a non-breaking change and eliminate the ugly pattern of always needing to declare variables outside of a try/catch/finally block simply because of the limitations of the current scoping support. Discuss... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
In a catch/finally block it is impossible to guarantee that any variables declared in the try block have been initialised, so this is a non starter me thinks |
Beta Was this translation helpful? Give feedback.
-
It is a breaking change that in order to keep scoping rules consistent it would be illegal to declare a new variable of the same name in the try {
int x = CalculateX();
}
finally {
int x = SomeOtherCalculation();
} Also, as @YairHalberstadt points out, given the exception could be thrown at nearly any point in the int x;
try {
x = CalculateX();
}
finally {
Console.WriteLine(x); // error CS0165: Use of unassigned local variable 'x'
} |
Beta Was this translation helpful? Give feedback.
It is a breaking change that in order to keep scoping rules consistent it would be illegal to declare a new variable of the same name in the
finally
block. This is legal today:Also, as @YairHalberstadt points out, given the exception could be thrown at nearly any point in the
try
block the variable would remain unassigned as far as thefinally
block is concerned. You can see this today by lifting the variable out of thetry
scope to the parent scope: