w0051977
w0051977

Reputation: 15807

VB.NET Returning an Object

Will the following statement cause a memory leak:

Imports System.Data.SQLClient

Public Function getConnection () As SQLConnection
    return New SQLConnection()
End Function

Public Sub TestConnection()
    Dim con As SQLConnection
    con = getConnection
    con.close
    con = Nothing
End Sub

How does .close or .dispose get called on the SQLConnection in getConnection?

Upvotes: 0

Views: 119

Answers (2)

Shahar G.
Shahar G.

Reputation: 1510

You're returning a reference type, hence you operate on the same instance in TestConnection so no memory leak here. At the end you have 2 instances with null (gc will collect them), but the connection is closed.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460108

There will be no memory leak because it will be garbage collected after you've called the method.

But this method does nothing but causing confusion. You should always dispose connections(which closes it implicitely) as soon as you're finished with it (even in case of an exception).

You can do that in a finally of a Try/Finally or (easier) with the Using statement. But since both approaches need to wrap the connection, your method enables the calling method to forget it. Therefore it is bad practise.

So simply do this:

Public Sub TestConnection()
    Using con = New SqlConnection("connection string here")
        Using cmd = new SqlCommand("sql query here", con)
            ' do something, f.e. cmd.ExecuteNonQuery() '
        End Using
    End Using
End Sub

Upvotes: 1

Related Questions