VB.NET when is it appropriate to set Object = Nothing?

Posted on 2008-11-10
Last Modified: 2012-08-13
When is it appropriate to set an object to nothing?

What about other things, large arrays? array lists? is this suggested or should i just let GC handle it?
Question by:mcainc
    LVL 69

    Accepted Solution

    by setting an object to nothing, you are helping the GC. If you set it, the GC can unallocate the object from memory on its first pass. if you don't, the GC first flag the object as potentially removable and on the second pass, if still marked as potential, removes it. you should always call .Close or .Dispose first.
    LVL 25

    Assisted Solution

    I think it goes out of scope sometimes and gets set to nothing. As emoreau mentioned it is better to call dispose on items when you don't need them anymore.  If you use Try Catch Finally then be sure to put the dispose in the Finally clause-if appropriate--to make sure that the object is disposed and set to nothing.

    The GC is non-deterministic...There's no way to know exactly when it will reclaim memory...except that it does so when it needs to.

    Sub Main()
         'call X
         'at this point the local variable g in sub X should be nothing...but the memory that was allocated may
         'or may not have yet been reclaimed by the GC; there is just no longer a reference to it..i.e.
         'we can no longer get to that memory
         'it is set to nothing because it was a local variable and went out of scope
         'a global variable...should you need one...doesn't go out of scope.  So there might be a case where
         'you needed it a while and then wanted to free the memory until you needed it again. Setting it to  
         'nothing allows the GC the chance to free it before you need to allocate something different for that  
    End Sub

    Sub X()
       dim g as new SOMEOBJECT

    End Sub

    Author Comment

    thanks guys, this is quite helpful

    a main reason i am asking & this may be a completely different ball game is that i am using this dll here in my .net project

    after several hours VM grows very large & nothing is re-claimed (program starts acting strangely, unstable)...

    I profiled this with ANTS several times and saw there were 400-500k live instances of string & 200-250k live instances of int32[] (regex) - all related to this dll

    i thought that was strange... so i added a button that would set that object = nothing however, the memory was never given back even after another hour or so of waiting

    i'm still trying to figure out how to fix that as i don't really know C# and there doesn't appear to be a dispose() that i can call either

    i tried to create my own Dispose() in the referencing class but it doesn't seem to do anything either, am I doing something wrong? is there anything i can do here to salvage this (I don't mind having to re-load the object every hour if necessary)?
    Imports AIMLbot
    Public Class ProgramNET
        Implements IDisposable
        Protected Overrides Sub Finalize()
        End Sub
        Public Sub Dispose() Implements System.IDisposable.Dispose
            Static done_before As Boolean = False
            If done_before Then Exit Sub
            done_before = True
            myBot = Nothing
            myUser = Nothing
            myReq = Nothing
        End Sub
        Dim myBot As New AIMLbot.Bot
        Dim myUser As New AIMLbot.User("user", myBot)
        Dim myReq As AIMLbot.Request
        Dim myRes As String = ""
        Public Sub New()
            myBot.isAcceptingUserInput = False
            myBot.isAcceptingUserInput = True
        End Sub
        Public Function Request(ByVal sUser As String, ByVal sMessage As String) As String
            Dim myReq = New AIMLbot.Request(sMessage, myUser, myBot)
            myRes = myBot.Chat(myReq).ToString
            myReq = Nothing
            Console.WriteLine("response: " & myRes)
            Return myRes
        End Function
    End Class

    Open in new window


    Featured Post

    Better Security Awareness With Threat Intelligence

    See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

    Join & Write a Comment

    Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
    A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now