When to close a datareader and connection?

I have the following code below in a shared function within a self-created namespace. My question is; when and where should I close the datareader and connection. I am assuming that in this example if I close the datareader after 'End While' it will be too late as the the function will have already executed its return of X.

I am assuming the same is true if I close the datareader after the 'End If'

Or am I completely wrong? and if so... where do I close the datareader/connection.
If oDR.HasRows = True Then
                    While oDR.Read
                        Return X
                    End While
                    Return 0
                End If

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You're correct, it would be too late.  Consider a variable to hold your return value, whether it is X or 0, and return it after the End If after you've closed the DataReader.

Also, if you're only going to return the one value, you don't need a while look.  If oDR.Read() then would accomplish the same.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
instead of returning x in the loop assign it to a variable.

the code will then exit out the loop and this is where you close your connection / reader.

the code will then exit the if statment and its here where you should return the value
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.