|
-
Apr 21st, 2006, 08:27 PM
#1
Interesting Return behavior
I haven't seen anybody comment on this yet, and I haven't been able to come up with some use for it, but it does seem like there ought to be something clever that you could do with it:
Consider these two short functions:
VB Code:
private function func1(ByRef n as integer) as integer
n=5
return n
n=6
end function
private function func2(ByRef n as integer) as integer
try
n=5
return n
catch ex as exception
'Do nothing here.
Finally
n=6
end try
end function
Now consider using the two in this fashion:
VB Code:
public sub Main()
dim v as integer
dim n as integer
n=0
v=func1(n)
'What does n equal? What does v equal?
n=0
v=func2(n)
end function
It may appear that after calling func1 or func2, the variables v and n would be set to the same thing. Afterall, the only difference between the two functions is that func2 has error handling, which will never be called because no errors will arise in that code.
However, the results will not be the same. After calling func1, both n and v will be set to 5. After calling func2, v is 5, but n is 6!
In func1, the function returns at the return statement, and the n=6 line is never executed. In func2, the return simply sets the return to 5, but then the finally block executes, and n is set to 6. Since n is passed by reference, it is changed.
I can't think of an obvious use for this, but it seems there is a window there to use a Finally block to do some odd things.
Any ideas?
My usual boring signature: Nothing
 
-
Apr 21st, 2006, 09:57 PM
#2
Re: Interesting Return behavior
Yes, the Finally block is executed regardless of whether there is an error or a return statement. It would be where you would put your Close for a file or database connection, so you'd only need to have it in the one place.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
-
Apr 21st, 2006, 10:09 PM
#3
Re: Interesting Return behavior
True, there are standard things that can be done there, but it seems like there ought to be some other use for a chunk of code that executes after the return statement. It's sort of like an OnClosing event in a window, but I have never actually used one of them for anything, either.
On the other hand, I realize now that I have done some stupid things because I didn't realize this behavior.
My usual boring signature: Nothing
 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|