Avatar of superbeast23
superbeast23

asked on 

How to properly dispose of objects in .NET

i have declared a module level variable m_oCon in a class called CDbSrvs.  can you please tell me if the cleanup code below is redundant.  if the dispose method is called does that implicitly call the close method?  does the variable need to be set to nothing or is that done in the dispose method as well?  what is the best practice for instantiating/destroying an object in .NET?
thanks,
dennis
        If Not m_oCon Is Nothing Then
            m_oCon.Close()
            m_oCon.Dispose()
            m_oCon = Nothing
          End If
Visual Basic.NET

Avatar of undefined
Last Comment
natloz
Avatar of superbeast23
superbeast23

ASKER

i forgot to mention that m_oCon is of type SqlConnection.
Avatar of Howard Cantrell
Howard Cantrell
Flag of United States of America image


If you use sample code, then you will not have the problem of disposing.

    Public Sub OpenDBSqlConnection()
        If sDBPass.Length = 0 Then
            sDBPass = ""
        End If
        Try
            Connect = New SqlConnection("Initial Catalog=" & sDBName & ";Data Source=" & sDBServer & ";User ID=" & sUSERid & ";password=" & sDBPass & ";")
            Connect.Open()
            Connect.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
            Cursor.Current = Cursors.Default
        End Try
    End Sub
ASKER CERTIFIED SOLUTION
Avatar of natloz
natloz

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo