declare DIM within TRY statement

  • Thread starter Thread starter wk6pack
  • Start date Start date
W

wk6pack

Hi,

I was wondering why when I declare the dim variable outside the try
statement, I could use the .dispose() function but when I declare it inside
the try statement, I get Name 'varname' is not declared.

thanks,
Will
 
Will,
It has to do with variable scope.

If you use:

Dim x As IDisposable
Try
Finally
x.Dispose
End Try

The x variable is at the same scope as the Try itself.

However if you do:

Try
Dim y As IDisposable
Finally
y.Dispose
End Try

The y variable is in the Try's block scope.

Remember that most block statements in VB.NET introduces a new block scope,
allowing each scope to define the same variable.

For details on Scope in VB.NET see:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vbconScope.asp

Hope this helps
Jay
 
wk6pack said:
I was wondering why when I declare the dim variable outside the try
statement, I could use the .dispose() function but when I declare it inside
the try statement, I get Name 'varname' is not declared.

Where are you trying to use it? In the finally block? If so, that's the
problem - the scope of the try block is just the try block, and with
good reason: the code execution might not have even reached the place
where your variable is declared before an exception is thrown.
 
thanks for the explanation and reference.

Will
Jay B. Harlow said:
Will,
It has to do with variable scope.

If you use:

Dim x As IDisposable
Try
Finally
x.Dispose
End Try

The x variable is at the same scope as the Try itself.

However if you do:

Try
Dim y As IDisposable
Finally
y.Dispose
End Try

The y variable is in the Try's block scope.

Remember that most block statements in VB.NET introduces a new block scope,
allowing each scope to define the same variable.

For details on Scope in VB.NET see:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vbconScope.asp

Hope this helps
Jay
 
Back
Top