473,321 Members | 1,667 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

'Set Object = Nothing'... do you still do this in VB.net????

I'm relatively new to VB.net. Is it good practice to 'destroy'
created objects... or does VB.net take care of this for you in its
'garbage' collection.

For example, in VB6 we used to have to do a lot of the following:

Set myObject = Nothing

....after we were finished using myObject. Is this still good practice
in VB.net?

Thanks in advance.
Oct 21 '07 #1
10 36358
You will get as many different answers as ther are programmers, however, the
short answer is No.

Now let me qualify that.

No, you are not required to assign Nothing to an object to 'destroy' it.

In general, when an object goes 'out of scope' it will become available for
garbage collection and the Garbage Collector will 'clean it up' when it gets
around to it.

There are some classes in the Framework where you MUST 'destroy' an instance
of it yourself. Off the top of my head, the WebRequest class is one.

Some classes expose a Dispose method. This indicates that an instance of the
class may make use of some unmanaged resources that need to be cleaned up.
For such objects you need to call the Dispose method of the object rather
than assigning Nothing to the object.

My recommendation is to NOT explicity 'destroy' objects at this stage of
your learning curve.

As you progress you will soon learn which objects you need to 'destroy'
whether it be by assigning Nothing or calling the Dispose method.

That said, you are free to explicity 'destroy' objects, a'la VB6, if you so
choose.
"Alan Mailer" <cl**********@earthlink.netwrote in message
news:7n********************************@4ax.com...
I'm relatively new to VB.net. Is it good practice to 'destroy'
created objects... or does VB.net take care of this for you in its
'garbage' collection.

For example, in VB6 we used to have to do a lot of the following:

Set myObject = Nothing

...after we were finished using myObject. Is this still good practice
in VB.net?

Thanks in advance.
Oct 21 '07 #2
Stephany Young <noone@localhostwrote:

<snip>
That said, you are free to explicity 'destroy' objects, a'la VB6, if you so
choose.
Just be aware that it won't actually do anything. In particular,
setting a variable's value to Nothing *doesn't* prompt the garbage
collector to collect the object the variable previously referred to.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 21 '07 #3
Tru Jon, but it does set it to Nothing which is useful in may ways,
including (for example):

Dim _object As Object = "ABC"

If _x then
_object = Nothing
...
End If

If _object Is Nothing Then Call GiveThatManACigar()
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Stephany Young <noone@localhostwrote:

<snip>
>That said, you are free to explicity 'destroy' objects, a'la VB6, if you
so
choose.

Just be aware that it won't actually do anything. In particular,
setting a variable's value to Nothing *doesn't* prompt the garbage
collector to collect the object the variable previously referred to.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 21 '07 #4
Stephany Young <noone@localhostwrote:
Tru Jon, but it does set it to Nothing which is useful in may ways,
including (for example):

Dim _object As Object = "ABC"

If _x then
_object = Nothing
...
End If

If _object Is Nothing Then Call GiveThatManACigar()
Oh sure - but it's important that people don't think that setting a
variable to nothing is in any way the same thing as "destroying an
object".

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 21 '07 #5
Stephany Young wrote:
There are some classes in the Framework where you MUST 'destroy' an
instance of it yourself. Off the top of my head, the WebRequest class
is one.
Assuming that is correct for the WebRequest class, how do you tell? There is
nothing I can see in the docs (framework 1.1) to say that must be done,
whereas, for example, System.Drawing.Bitmap has a Dispose() method, although
I suppose you have to infer from the existence of a Dispose() method that it
needs to be called.

Andrew
Oct 22 '07 #6
Andrew Morton <ak*@in-press.co.uk.invalidwrote:
Stephany Young wrote:
There are some classes in the Framework where you MUST 'destroy' an
instance of it yourself. Off the top of my head, the WebRequest class
is one.

Assuming that is correct for the WebRequest class, how do you tell? There is
nothing I can see in the docs (framework 1.1) to say that must be done,
whereas, for example, System.Drawing.Bitmap has a Dispose() method, although
I suppose you have to infer from the existence of a Dispose() method that it
needs to be called.
You need to know that the class implements IDisposable. WebRequest was
an unfortunate example, as unfortunately it *doesn't* require disposal,
not implementing IDisposable.

WebReponse, however, is a reasonable example.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 22 '07 #7
When "myObject" is a local variable of your subroutine, it is actually
a bad practice to set it to Nothing at the end of the body. That is
equivalent to calling GC.KeepAlive(). It prevents the object from
getting collected as early as it can be if the collection happens to
start just as the subroutine is busy executing but the remainder of
the body has no more references to the variable.

The garbage collector is smart enough to know when a live reference to
object is itself no longer alive so that both the object containing
the reference as well as the object itself can be collected. There's
no need to help it by setting the reference to Nothing/null. That
also alleviates the pain of having to write try / finally blocks to
set the references to null. The only exception I can think of is when
the object reference is a field of a class and the reference is
temporary.

Forgetting to call Dispose() when a class implements it is not
something you'd typically notice. Your app just runs a bit "heavy",
holding on to unmanaged operating system resources longer than
necessary. After a garbage collection occurs, the finalizer ensures
the Dispose code runs to release the resources. Note however that you
do risk OOM, particularly when you use an object that uses lots of
unmanaged memory but very little GC heap space. Bitmap is a good
example. The one and only example I know of where not calling
Dispose() causes a leak: using a BindingSource on a Windows Forms
dialog and not calling Dispose() on the form after ShowDialog()
returns.
Oct 23 '07 #8
On Oct 23, 1:59 pm, hpass...@gmail.com wrote:
When "myObject" is a local variable of your subroutine, it is actually
a bad practice to set it to Nothing at the end of the body. That is
equivalent to calling GC.KeepAlive(). It prevents the object from
getting collected as early as it can be if the collection happens to
start just as the subroutine is busy executing but the remainder of
the body has no more references to the variable.
Unless VB.NET is doing something different to C#, it makes no
difference in release mode. The GC/JIT is clever enough to realise
that there will be no more *reads* of the variable - the can be
collected before the assignment is made.

Here's a sample app which shows this:

using System;

class Test
{
~Test()
{
Console.WriteLine("Finalizer called");
}

static void Main()
{
Console.WriteLine ("Before creation");
Test t = new Test();

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine ("Before assignment");
t = null;
}
}

<snip>
Forgetting to call Dispose() when a class implements it is not
something you'd typically notice. Your app just runs a bit "heavy",
holding on to unmanaged operating system resources longer than
necessary. After a garbage collection occurs, the finalizer ensures
the Dispose code runs to release the resources. Note however that you
do risk OOM, particularly when you use an object that uses lots of
unmanaged memory but very little GC heap space. Bitmap is a good
example. The one and only example I know of where not calling
Dispose() causes a leak: using a BindingSource on a Windows Forms
dialog and not calling Dispose() on the form after ShowDialog()
returns.
Memory is just one resource, however. More importantly, failure to
dispose of streams and database connections can leave files locked and
use pooled connections way beyond the desired time.

Basically, it's important to call Dispose, and shouldn't be thought of
as an optional extra.

Jon

Oct 23 '07 #9
On Oct 21, 10:11 am, Alan Mailer <clarityas...@earthlink.netwrote:
I'm relatively new to VB.net. Is it good practice to 'destroy'
created objects... or does VB.net take care of this for you in its
'garbage' collection.

For example, in VB6 we used to have to do a lot of the following:

Set myObject = Nothing

...after we were finished using myObject. Is this still good practice
in VB.net?

Thanks in advance.
Alan,

You will find lot of discussion on this.... But as per my exp. there
is no use to setting object = Nothing in VB.NET
The only advantage (May be) is after you set the object = Nothing its
reference count will be reseted to 0 which makes this object as best
candidate to be collected by GC...

So while working with VB.NET there is no use to setting object =
nothing...But keep in mind.. if object is expensive then its better to
dispose the object.

Setting object = Nothing doesnot gurantee that it will be collected
by GC sooon

Parikshit
Nov 15 '07 #10
On Nov 15, 12:52 pm, Parikshit Sehgal <ppseh...@gmail.comwrote:

<snip>
The only advantage (May be) is after you set the object = Nothing its
reference count will be reseted to 0 which makes this object as best
candidate to be collected by GC...
No - because objects *aren't reference counted*.

The only use is if you're within a loop or some other construct where
the JIT can't tell that you're not going to use the object again. For
instance (C# code, same applies in VB):

// Large object only needed in the first iteration of the loop
SomeObject foo = new SomeObject();
bool firstTime = true;

// Potentially long running loop
while (ReadData())
{
if (firstTime)
{
foo.DoSomething();
firstTime = false;
foo = null;
}
}

Jon
Nov 15 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Tony | last post by:
Hi, anyone have better information on IIS 5.0 memory behaviour on setting objects to nothing? Connections and recordsets of course should be set to nothing, but should for example XMLNode...
6
by: dotnettester | last post by:
Woud this work? ..... Response.end set objConn = nothing set objAnyObject = nothing ?
2
by: Paul T. Rong | last post by:
Sorry I just lost tracks of a series of posts, so I post my question again, hoping someone can help. Here is codes provided by Jeff Smith > Private Sub Form_Load() > Dim db As...
0
by: David Hodges | last post by:
After installing the service packs from Framework 1.0 and 1.1 on my W2k web server I get the above error on all applications. I am at my wits end and finding nothing on Google that helps. Here...
2
by: Slim | last post by:
I must admit I always forget to use "response.end" and I also forget to "set objects = nothing" how important are these things. I know my application run fine without them probably because I...
4
by: Paul H | last post by:
A typical chunk of code...... Set db = CurrentDb Set rs = db.OpenRecordset("tblFoo") <Do some stuff here> 'How much of the stuff below do I need? 'Do I need to close the recordset?...
13
by: | last post by:
Hi all, Coming from the good old VB6 days we were told to always destroy our objects as follows:- Dim obj as New MyObject ' do some work with obj obj = Nothing I have been doing this in...
34
by: =?Utf-8?B?SGFvIEppYW5n?= | last post by:
Hi, I see in many MS example code that looks like this Public Sub Foo() dim myCustomer as New Customer ... myCustomer.Dispose() myCustomer = Nothing End Sub
4
by: Joergen Bech | last post by:
I sometimes use delegates for broadcasting "StateChanged" events, i.e. if I have multiple forms and/or controls that need updating at the same time as the result of a change in a global/common...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.