dcsimg


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 5 123 ... LastLast
Results 1 to 15 of 65

Thread: Set MyObject=Nothing?

  1. #1
    Peter Guest

    Set MyObject=Nothing?


    Simple question but not so sure about right answer:

    What is the purpose of using the following line of code – “Set MyObject =
    NOTHING”, and how to use it?

    Thanks.

    Peter



  2. #2
    Arthur Wood Guest

    Re: Set MyObject=Nothing?


    Whenever an object is instantiated, memory is allocated to the variables and
    code which comprise that object. This is the case whether the object is
    an instance of a form, or a Connection, or whatever. The purpose of the
    Set MyObject = Nothing is to release that allocated memory back to free storage.
    Usually this will happen automatically, whenver the decalration of MyObject
    goes out of scope, but it is good programming style to free the space as
    soon as it is no longer needed in your code. It is also good style to free
    the space yourself, rather tahn relying on VB to free it for you.

    Arthur Wood

    "Peter" <peterchen6@hotmail.com> wrote:
    >
    >Simple question but not so sure about right answer:
    >
    >What is the purpose of using the following line of code – “Set MyObject

    =
    >NOTHING”, and how to use it?
    >
    >Thanks.
    >
    >Peter
    >
    >



  3. #3
    Anthony Jones Guest

    Re: Set MyObject=Nothing?

    Peter,

    The purpose of the Set MyObject = Nothing is to release a reference to an
    object.

    All COM objects have an interface known as IUnknown (pardon the oxymoron).
    It has there members QueryInterface, AddRef, Release.

    MyObject will hold a pointer to an interface on the object which it got
    through a call to QueryInterface or a copy of an existing pointer after
    which AddRef will have been called. Both QueryInterface and AddRef cause
    the object to increase it's internal count of referencers.

    If you were to set a reference to another object into MyObject (or in this
    case zero the pointer it holds) VB calls Release which decrements the
    objects count. When the objects count reachs zero it will assume it is no
    longer needed and should release it's resources.

    When object variable passes out of scope VB will call release if it still
    holds a pointer.

    As to good programming style I disagree with Arthur, I find a sequence of
    (Set x = Nothing) statements at the bottom of procedures to be clutter I
    can do with out.

    --
    Anthony Jones
    Nuesoft Ltd




  4. #4
    John Perkins Guest

    Re: Set MyObject=Nothing?


    Anthony,

    There are some cases, notably with forms that are called implicitly without
    an object variable, where VB behaves differently if you don't set an object
    to nothing.

    It is easier to demonstrate this than to describe it. Create a VB project
    with two forms: Form1 and Form2. On Form1, put a Command1 button. On Form2,
    put a Command1 button and a Text1 textbox.

    Paste this code into Form1:

    Option Explicit

    Private Sub Command1_Click()

    Form2.Init
    Form2.Show

    ' When the form is not set to nothing, it doesn't really
    ' go away. Try un-commenting this line and see the results.
    ' Set Form2 = Nothing

    End Sub

    Paste this code into Form2:

    Option Explicit

    Private m_formIsLoaded As Boolean

    Public Sub Init()

    If Not m_formIsLoaded Then
    Text1.Text = "foo"
    m_formIsLoaded = True
    End If

    End Sub

    Private Sub Command1_Click()

    Unload Me

    End Sub


    After running the code, you will see why some people think you should always
    set things to "nothing". I agree with you, however. You don't need to set
    objects to nothing when you don't need to. It's just that VB doesn't make
    it easy for novice's to know when they don't need to, that's why people tend
    to recommend doing it all the time.

    -John Perkins


    "Anthony Jones" <yadayadayada@msn.com> wrote:
    snip
    >When object variable passes out of scope VB will call release if it still
    >holds a pointer.
    >
    >As to good programming style I disagree with Arthur, I find a sequence of
    >(Set x = Nothing) statements at the bottom of procedures to be clutter I
    >can do with out.
    >
    >--
    >Anthony Jones
    >Nuesoft Ltd
    >
    >
    >



  5. #5
    John Perkins Guest

    Re: Set MyObject=Nothing?


    Forgot to mention this expressly in the e-mail, but in the demo code, you
    should click the Form1.Command1 button twice while running to see the behavior
    in each case.

    -John Perkins

    "John Perkins" <perk_j@yahoo.com> wrote:
    >
    >Anthony,
    >
    >There are some cases, notably with forms that are called implicitly without
    >an object variable, where VB behaves differently if you don't set an object
    >to nothing.
    >
    >It is easier to demonstrate this than to describe it. Create a VB project
    >with two forms: Form1 and Form2. On Form1, put a Command1 button. On Form2,
    >put a Command1 button and a Text1 textbox.
    >
    >Paste this code into Form1:
    >
    >Option Explicit
    >
    >Private Sub Command1_Click()
    >
    > Form2.Init
    > Form2.Show
    >
    > ' When the form is not set to nothing, it doesn't really
    > ' go away. Try un-commenting this line and see the results.
    >' Set Form2 = Nothing
    >
    >End Sub
    >
    >Paste this code into Form2:
    >
    >Option Explicit
    >
    >Private m_formIsLoaded As Boolean
    >
    >Public Sub Init()
    >
    > If Not m_formIsLoaded Then
    > Text1.Text = "foo"
    > m_formIsLoaded = True
    > End If
    >
    >End Sub
    >
    >Private Sub Command1_Click()
    >
    > Unload Me
    >
    >End Sub
    >
    >
    >After running the code, you will see why some people think you should always
    >set things to "nothing". I agree with you, however. You don't need to set
    >objects to nothing when you don't need to. It's just that VB doesn't make
    >it easy for novice's to know when they don't need to, that's why people

    tend
    >to recommend doing it all the time.
    >
    >-John Perkins
    >
    >
    >"Anthony Jones" <yadayadayada@msn.com> wrote:
    >snip
    >>When object variable passes out of scope VB will call release if it still
    >>holds a pointer.
    >>
    >>As to good programming style I disagree with Arthur, I find a sequence

    of
    >>(Set x = Nothing) statements at the bottom of procedures to be clutter

    I
    >>can do with out.
    >>
    >>--
    >>Anthony Jones
    >>Nuesoft Ltd
    >>
    >>
    >>

    >



  6. #6
    Mark Alexander Bertenshaw Guest

    Re: Set MyObject=Nothing?

    Arthur -

    According to Matt Curland's book, ritually setting an object variable to
    Nothing is pointless if the variable is declared on the stack i.e. in
    procedure scope, and by doing so, you are simply duplicating a couple of
    extra instructions which the VB compiler adds itself to release references.

    Having said that, up to now I have religiously done this as well, and
    breaking this habit will be difficult <g>.

    "Arthur Wood" <wooda@saic-trsc.com> wrote in message
    news:39ef8dec$1@news.devx.com...
    >
    > Whenever an object is instantiated, memory is allocated to the variables

    and
    > code which comprise that object. This is the case whether the object is
    > an instance of a form, or a Connection, or whatever. The purpose of the
    > Set MyObject = Nothing is to release that allocated memory back to free

    storage.
    > Usually this will happen automatically, whenver the decalration of

    MyObject
    > goes out of scope, but it is good programming style to free the space as
    > soon as it is no longer needed in your code. It is also good style to

    free
    > the space yourself, rather tahn relying on VB to free it for you.
    >
    > >What is the purpose of using the following line of code – “Set MyObject
    > >NOTHING”, and how to use it?


    --
    Mark Alexander Bertenshaw
    Programmer/Analyst
    PrimeResponse
    Brentford
    UK



  7. #7
    Bob Butler Guest

    Re: Set MyObject=Nothing?

    "Mark Alexander Bertenshaw" <mark.bertenshaw@virgin.net> wrote in message
    news:39f1bb86@news.devx.com...
    > Arthur -
    >
    > According to Matt Curland's book, ritually setting an object variable to
    > Nothing is pointless if the variable is declared on the stack i.e. in
    > procedure scope, and by doing so, you are simply duplicating a couple of
    > extra instructions which the VB compiler adds itself to release

    references.
    >
    > Having said that, up to now I have religiously done this as well, and
    > breaking this habit will be difficult <g>.


    Why break it? I find that having explicit code to release an object makes
    it easier to read and maintain. Yes, it will be released anyway but relying
    on any default behavior is always risky. When you look at the changes made
    in VB.Net I see explicit shutdown code for every object to be even more
    important than ever and having the "Set =nothing" all in one place makes it
    easier to go through and make sure you are closing them all down properly.




  8. #8
    mrfelis Guest

    Re: Set MyObject=Nothing?

    This is not a good example John. VB adds variables Form1 and Form2 to the
    project's symbol table (or whatever VB calls the symbol table). This can be
    visualized by thinking of an BAS module in the project which contains the
    following declarations:

    Public Form1 As New Form1
    Public Form2 As New Form2

    As you add/remove/rename the forms through the IDE, VB will alter these
    entries in the symbol table. So if you change Form2's name to frmTest, VB
    will change the declaration to:

    Public Form1 As New Form1
    Public frmTest As New frmTest

    Knowing this let's look at the code again (assuming the first click):
    >
    > Option Explicit
    >
    > Private Sub Command1_Click()


    At this point Form2 is nothing. The only way to see this is to put a
    breakpoint on or before the next line and inspect Form2.

    > Form2.Init

    VB creates a Form2 object, assigns the object to the global object variable,
    Form2, that VB created for you. The ref count for the object is increased by
    1. Finally, VB calls the Init method of this object. The form is initialized
    soemwhere in this mess of code VB adds for you.

    > Form2.Show

    Had Init not caused the Form2 object to load, VB would load the form for you
    now as well as showing it. Once the form loads VB adds the form to the Forms
    Collection. This increases the ref count of the object by 1 again. So the
    Form2 object's ref count is at least 2 at this point.

    > ' When the form is not set to nothing, it doesn't really
    > ' go away. Try un-commenting this line and see the results.
    > ' Set Form2 = Nothing


    In doing this, you release 1 reference to Form2 objects Ref Count by 1.
    Since the Forms collection has a reference to this Form2 object the object
    remains instantiated. The only way to get the Form2 object out of the Forms
    collection is to Unload it.

    > End Sub
    >


    VB isn't really acting differently. MS just did some things behind the
    scenes that (while violating good programming practice) make it easier to
    get started doing things.

    --
    ~~~
    C'Ya,
    mrfelis
    mrfelis@yahoo.NOSPAM.com
    just remove the spam



  9. #9
    Andy Chevin Guest

    Re: Set MyObject=Nothing?

    Bob,

    > Why break it? I find that having explicit code to release an object makes
    > it easier to read and maintain. Yes, it will be released anyway but

    relying
    > on any default behavior is always risky.


    I don't see how having extraneous code adds to readabilty or
    maintainability. Exactly the opposite.
    And what risk? This is how VB works. You can rely on it - there is no
    evidence to the contrary.
    It's like setting all numeric vars to zero at the bottom of a routine, but
    you don't do that (do you?).

    Andy.




  10. #10
    John Perkins Guest

    Re: Set MyObject=Nothing?


    mrfelis,

    It is a good example as it illustrates exactly what I am talking about. You
    obviously didn't run the code twice and see the difference when you hit Command1
    the second time after you've clicked Command1 on Form2 in each case. In the
    case where you don't set the object to nothing, VB "keeps" the implicit form
    object variable for you somewhere in memory; part of VB's optimization.

    Try the code again. First comment out the set = nothing line. Click Command1
    on Form1. Look at the results in Form2. Click Form2.Command1 to "Unload"
    the form. Click Form1.Command1 again.

    Now do the same with the Set Form2 = Nothing line not commented out.

    -John Perkins


    "mrfelis" <mrfelis@yahoo.NOSPAM.com> wrote:
    >This is not a good example John. VB adds variables Form1 and Form2 to the
    >project's symbol table (or whatever VB calls the symbol table). This can

    be
    >visualized by thinking of an BAS module in the project which contains the
    >following declarations:
    >
    >Public Form1 As New Form1
    >Public Form2 As New Form2
    >
    >As you add/remove/rename the forms through the IDE, VB will alter these
    >entries in the symbol table. So if you change Form2's name to frmTest, VB
    >will change the declaration to:
    >
    >Public Form1 As New Form1
    >Public frmTest As New frmTest
    >
    >Knowing this let's look at the code again (assuming the first click):
    >>
    >> Option Explicit
    >>
    >> Private Sub Command1_Click()

    >
    >At this point Form2 is nothing. The only way to see this is to put a
    >breakpoint on or before the next line and inspect Form2.
    >
    >> Form2.Init

    >VB creates a Form2 object, assigns the object to the global object variable,
    >Form2, that VB created for you. The ref count for the object is increased

    by
    >1. Finally, VB calls the Init method of this object. The form is initialized
    >soemwhere in this mess of code VB adds for you.
    >
    >> Form2.Show

    >Had Init not caused the Form2 object to load, VB would load the form for

    you
    >now as well as showing it. Once the form loads VB adds the form to the Forms
    >Collection. This increases the ref count of the object by 1 again. So the
    >Form2 object's ref count is at least 2 at this point.
    >
    >> ' When the form is not set to nothing, it doesn't really
    >> ' go away. Try un-commenting this line and see the results.
    >> ' Set Form2 = Nothing

    >
    >In doing this, you release 1 reference to Form2 objects Ref Count by 1.
    >Since the Forms collection has a reference to this Form2 object the object
    >remains instantiated. The only way to get the Form2 object out of the Forms
    >collection is to Unload it.
    >
    >> End Sub
    >>

    >
    >VB isn't really acting differently. MS just did some things behind the
    >scenes that (while violating good programming practice) make it easier to
    >get started doing things.
    >
    >--
    >~~~
    >C'Ya,
    >mrfelis
    >mrfelis@yahoo.NOSPAM.com
    >just remove the spam
    >
    >



  11. #11
    John Perkins Guest

    Re: Set MyObject=Nothing?


    mrfelis,

    Also, your analysis of my code is incorrect anyway because you neglected
    to notice that I was unloading form2 in when you click Form2.Command1.

    Private Sub Command1_Click()

    Unload Me

    End Sub


    -John Perkins

    "mrfelis" <mrfelis@yahoo.NOSPAM.com> wrote:
    >This is not a good example John. VB adds variables Form1 and Form2 to the
    >project's symbol table (or whatever VB calls the symbol table). This can

    be
    >visualized by thinking of an BAS module in the project which contains the
    >following declarations:
    >
    >Public Form1 As New Form1
    >Public Form2 As New Form2
    >
    >As you add/remove/rename the forms through the IDE, VB will alter these
    >entries in the symbol table. So if you change Form2's name to frmTest, VB
    >will change the declaration to:
    >
    >Public Form1 As New Form1
    >Public frmTest As New frmTest
    >
    >Knowing this let's look at the code again (assuming the first click):
    >>
    >> Option Explicit
    >>
    >> Private Sub Command1_Click()

    >
    >At this point Form2 is nothing. The only way to see this is to put a
    >breakpoint on or before the next line and inspect Form2.
    >
    >> Form2.Init

    >VB creates a Form2 object, assigns the object to the global object variable,
    >Form2, that VB created for you. The ref count for the object is increased

    by
    >1. Finally, VB calls the Init method of this object. The form is initialized
    >soemwhere in this mess of code VB adds for you.
    >
    >> Form2.Show

    >Had Init not caused the Form2 object to load, VB would load the form for

    you
    >now as well as showing it. Once the form loads VB adds the form to the Forms
    >Collection. This increases the ref count of the object by 1 again. So the
    >Form2 object's ref count is at least 2 at this point.
    >
    >> ' When the form is not set to nothing, it doesn't really
    >> ' go away. Try un-commenting this line and see the results.
    >> ' Set Form2 = Nothing

    >
    >In doing this, you release 1 reference to Form2 objects Ref Count by 1.
    >Since the Forms collection has a reference to this Form2 object the object
    >remains instantiated. The only way to get the Form2 object out of the Forms
    >collection is to Unload it.
    >
    >> End Sub
    >>

    >
    >VB isn't really acting differently. MS just did some things behind the
    >scenes that (while violating good programming practice) make it easier to
    >get started doing things.
    >
    >--
    >~~~
    >C'Ya,
    >mrfelis
    >mrfelis@yahoo.NOSPAM.com
    >just remove the spam
    >
    >



  12. #12
    Bob Butler Guest

    Re: Set MyObject=Nothing?

    "Andy Chevin" <yoshimura.freeserve.co.uk> wrote in message
    news:39f1e100@news.devx.com...
    > > Why break it? I find that having explicit code to release an object

    makes
    > > it easier to read and maintain. Yes, it will be released anyway but

    > relying
    > > on any default behavior is always risky.

    >
    > I don't see how having extraneous code adds to readabilty or
    > maintainability. Exactly the opposite.
    > And what risk? This is how VB works. You can rely on it - there is no
    > evidence to the contrary.
    > It's like setting all numeric vars to zero at the bottom of a routine, but
    > you don't do that (do you?).


    Just a matter of style more than anything else. I ensure all objects are
    released but you are right that I don't set numerics to zero because that
    isn't at all the same thing.... changing the value containe din a numeric
    does nothing. Setting an object reference to Nothing has effects beyond the
    value contained in the object variable and I simply like doing that under my
    control rather than leaving it to VB. Personally I find it more
    maintainable, especially when working with code somebody else wrote. If you
    find it the opposite then I can't argue with that but I'm also going to keep
    doing it on code I work with <g>

    As far as risk goes, when VB.Net comes out things change drastically. You
    still won't need to set objects to Nothing but you will probably have to do
    some sort of cleanup call on each because otherwise they hang around in
    memory indefinitely and you never know when the "Finalize" will happen. In
    my code I always have explicit "Set =nothing" statements and error handling
    to ensure they are called so I know exactly where to add any necessary
    cleanup code that VB.Net objects will need. Code that does not explicitly
    deal with object termination now is probably going to need much closer
    examination to migrate.




  13. #13
    Michael Culley Guest

    Re: Set MyObject=Nothing?


    Bob,

    A better example would be do you set variables to default values at the start
    of functions?

    I had a poke around to see what VB does and it seams that it still does the
    Set Obj=Nothing itself even if you do it.

    There is one case where I use it and that is in terminate events for object
    dimmed at the module level.

    Michael Culley

    "Bob Butler" <butlerbob@deja.com> wrote:
    >"Andy Chevin" <yoshimura.freeserve.co.uk> wrote in message
    >news:39f1e100@news.devx.com...
    >> > Why break it? I find that having explicit code to release an object

    >makes
    >> > it easier to read and maintain. Yes, it will be released anyway but

    >> relying
    >> > on any default behavior is always risky.

    >>
    >> I don't see how having extraneous code adds to readabilty or
    >> maintainability. Exactly the opposite.
    >> And what risk? This is how VB works. You can rely on it - there is no
    >> evidence to the contrary.
    >> It's like setting all numeric vars to zero at the bottom of a routine,

    but
    >> you don't do that (do you?).

    >
    >Just a matter of style more than anything else. I ensure all objects are
    >released but you are right that I don't set numerics to zero because that
    >isn't at all the same thing.... changing the value containe din a numeric
    >does nothing. Setting an object reference to Nothing has effects beyond

    the
    >value contained in the object variable and I simply like doing that under

    my
    >control rather than leaving it to VB. Personally I find it more
    >maintainable, especially when working with code somebody else wrote. If

    you
    >find it the opposite then I can't argue with that but I'm also going to

    keep
    >doing it on code I work with <g>
    >
    >As far as risk goes, when VB.Net comes out things change drastically. You
    >still won't need to set objects to Nothing but you will probably have to

    do
    >some sort of cleanup call on each because otherwise they hang around in
    >memory indefinitely and you never know when the "Finalize" will happen.

    In
    >my code I always have explicit "Set =nothing" statements and error handling
    >to ensure they are called so I know exactly where to add any necessary
    >cleanup code that VB.Net objects will need. Code that does not explicitly
    >deal with object termination now is probably going to need much closer
    >examination to migrate.
    >
    >
    >



  14. #14
    Bob Butler Guest

    Re: Set MyObject=Nothing?

    "Michael Culley" <m_culley@one.net.au> wrote in message
    news:39f2d315$1@news.devx.com...
    > A better example would be do you set variables to default values at the

    start
    > of functions?


    That's still not a good example but in most cases if I depend on a specific
    value being there I do set it, even if it is the default. I've been burned
    more than once in various languages when default behavior changed and I've
    learned not to rely on it when I can easily avoid it.

    > I had a poke around to see what VB does and it seams that it still does

    the
    > Set Obj=Nothing itself even if you do it.


    Yes, it does. I do not argue that. What I do believe is that having the
    code do it explicitly shows me exactly when and where in my code I no longer
    need it. It also serves to remind me to call any .Close or other method
    needed to shut down cleanly. I see a lot of code where people rely on the
    variable going out of scope and then rely on the termination doing
    cleanup... I've always held that better to take complete control over the
    lifetime of any objects you use and the upcoming changes in VB.Net are going
    to force people to do just that in a lot more cases.

    The current versions of VB handle it for you and do it properly (at least in
    most cases - I do not know offhand of any objects that do not shut down
    cleanly now although I have seen them in the past. One early DAO version,
    for example, did not properly release resources if you did not explicitly
    close recordsets and/or databases.) If you are comfortable in relying on
    the VB cleanup now then by all means do so. I always try to code with an
    eye towards moving to new versions and/or other languages down the line so I
    prefer to be as explicit as possible. For me it has paid off in the past
    and it looks like it's going to make VB.Net easier to adopt.

    > There is one case where I use it and that is in terminate events for

    object
    > dimmed at the module level.


    Why? When the module goes out of scope, or the app ends, the references
    will be released. You don't trust VB to do that correctly somehow? As long
    as you do not have circular references set up it will all be handled
    automatically...

    As far as I'm concerned, always releasing references lets you control the
    order and timing and makes the code more self-documenting.



  15. #15
    Anthony Jones Guest

    Re: Set MyObject=Nothing?

    Bob,

    Do you also do the following to all your string variables

    str = vbNullString

    at the end of all your procedures?

    OR

    Do you rely on the 'risky' default behavior of VB calling SysFreeString for
    you?

    If the latter is true, why would you trust VB call SysFreeString but not
    trust it to call IUnknown.Release?

    --
    Anthony Jones
    Nuesoft Ltd




Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center