Thursday, September 07, 2006

Scoping issues in C#

Came across some "interesting" scoping rules of C# at work today.Consider the following:

try {
int answer = 42;
} catch {
// ...
}
int answer = 42;

This one errors out with the somewhat curious error message:
Error 1 A local variable named 'answer' cannot be declared in this scope because it would give a different meaning to 'answer', which is already used in a 'child' scope to denote something else C:\Path\To\File.cs 15 17 TheProject

Out of curiosity we tried the following:

try {
int answer = 42;
} catch {
// ...
}
answer = 42;


This (rightfully IMO) errors out in the following way (the same thing happens by the way if the second assignment is within the catch block):
Error 1 The name 'answer' does not exist in the current context C:\Path\To\File.cs 15 13 TheProject

No comments: