Datareader passed ByVal - OOP Basics question

J

Juxx

Hi All,

I've a big doubt about reference to object destruction.

In the test below I call 2 times a sub passing a datareader in 2
different ways.

Who can tell me if datareader is destroyed in both cases and
so connection closed (using dr behavior)?


*-*-*-*
Case 1
*-*-*-*
Dim cm As SqlCommand
Dim dr As SqlDataReader = cm.ExecuteReader(CommandBehavior.CloseConnection)

' Datareader is passed ByVal to MySub
' I have to close "dr" here and "otherdr" in MySub
MySub(dr)

dr.Close()
dr = Nothing

*-*-*-*
Case 2
*-*-*-*
Dim cm As SqlCommand

' No reference to datareader exist (?) at this level,
' I have only to close "otherdr" in MySub ?
MySub(cm.ExecuteReader(CommandBehavior.CloseConnection))

*-*-*-*
MySub
*-*-*-*
Sub MySub(ByVal otherdr As SqlDataReader)
While otherdr.Read
' Do something
End While
otherdr.Close()
otherdr = Nothing
End Sub
 
M

Miha Markic

Hi,

I guess either way will do.
However, you might use the pattern of closing reader at the same level
you've opened it - that would be case 1.
You might also embedd it into try/finally block so you make sure it is
closed.
 
W

William Ryan

Guilo:

A few things...1) A datareader is a reference type so even though you are
passing it byVal, it's still a reference type and you are only passing a
copy of the reference to the sub.
2) As far as teh connection goes and when it dies, I don't think you can
tell from this code snippet. If it's declared at the module level and still
visible after the calls to the sub, and they are still referenced in the
calling code, just b/c the connection is closed doesn't means it's 'died'
3) You did the cleanup, but you can't tell when a garbage collection is
going to happen (or if it will).

HTH,

Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top