473,667 Members | 2,670 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

object = nothing?

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 .Net also for quite a while now. The other day one
of my peers mentioned that this is a BIG NO NO and that I should let the
Garbage Collection process handle this for me.

Can someone share any insight on this?

TIA!
Oct 21 '06 #1
13 4518
It is safe to set your objects to Nothing. They will immediately be marked
for garbage collection. If you skip the assignment to Nothing, they will
still be marked for gargabe collection once they go out of scope and there
are no other references to the objects. For most local variables, this occurs
when you exit the function or subroutine.

Some objects need a little more attention. If an object supports the IDisposable
interface, it includes a Dispose method that should be called before you
are finished with it. This guarantees that any acquired resources are released
before garbage collection. The new Visual Basic 2005 Using keyword will help
with this process.

-----
Tim Patrick
Start-to-Finish Visual Basic 2005
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 .Net also for quite a while now. The other
day one of my peers mentioned that this is a BIG NO NO and that I
should let the Garbage Collection process handle this for me.

Can someone share any insight on this?

TIA!

Oct 21 '06 #2
<pa***@communit y.nospamschrieb :
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 .Net also for quite a while now. The other day
one of my peers mentioned that this is a BIG NO NO and that I should let
the Garbage Collection process handle this for me.
Your peer is right and he isn't.

Note that COM used reference counting to detect whether or not an object
should be destroyed. .NET uses a different approach. The garbage collector
checks objects in certain periods of time and destroys them if necessary
(this is simplified, I suggest to read the chapters about garbage collection
and the garbage collector (GC) in the documentation). Thus setting a
variable to 'Nothing' does not necessarily destroy the object immediately if
no other references are pointing to it.

Because of the evolvedness of .NET's garbage collector it is not even
necessary to clear all references to an object to be able to destroy it. If
two objects reference each other but are not reachable from the
application's code any more, the garbage collector will detect this and will
clean up the objects after some time.

So the conclusion is: Setting local variables to 'Nothing' at the end of
the procedure does not make any sense. This applies to VB6 too. Setting
variables to 'Nothing' prior to assigning another reference to the variable
does not make any sense at all too, even not in VB6. It may however make
sense to set private variables or properties to 'Nothing' to speed up
cleanup and maintain a valid state.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Oct 21 '06 #3
Herfried K. Wagner [MVP] wrote:
Setting variables to 'Nothing' prior to assigning another reference to
the variable does not make any sense at all too, even not in VB6.
Actually, there is a situation in VB6 where it does make sense. Example:

Set objRs = objConnection.E xecute("select something from sometable")
lngValue = objRs(0)
objRs.Close()
Set objRs = Nothing
Set objRs = objConnection.E xecute("select something from someothertable" )
lngValue2 = objRs(0)
objRs.Close()

Removing the reference before creating a new recordset will return the
first recordset to the object pool. When the next recordset is created,
it can be reused from the object pool. If you don't remove the
reference, the first recordset will not be returned to the object pool
until after the second has been created.
Oct 22 '06 #4
So in theory setting an object to Nothing, if not anything should help the
GC in doing its job right? Since objects will be better identified as
candidates for garbage collection?

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.atwrote in message
news:uz******** ******@TK2MSFTN GP03.phx.gbl...
<pa***@communit y.nospamschrieb :
>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 .Net also for quite a while now. The other day
one of my peers mentioned that this is a BIG NO NO and that I should let
the Garbage Collection process handle this for me.

Your peer is right and he isn't.

Note that COM used reference counting to detect whether or not an object
should be destroyed. .NET uses a different approach. The garbage
collector checks objects in certain periods of time and destroys them if
necessary (this is simplified, I suggest to read the chapters about
garbage collection and the garbage collector (GC) in the documentation).
Thus setting a variable to 'Nothing' does not necessarily destroy the
object immediately if no other references are pointing to it.

Because of the evolvedness of .NET's garbage collector it is not even
necessary to clear all references to an object to be able to destroy it.
If two objects reference each other but are not reachable from the
application's code any more, the garbage collector will detect this and
will clean up the objects after some time.

So the conclusion is: Setting local variables to 'Nothing' at the end of
the procedure does not make any sense. This applies to VB6 too. Setting
variables to 'Nothing' prior to assigning another reference to the
variable does not make any sense at all too, even not in VB6. It may
however make sense to set private variables or properties to 'Nothing' to
speed up cleanup and maintain a valid state.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Oct 22 '06 #5
Hello ,,,

Well you have started something :-) ....... this has been discussed manny
times in this group and it always ends the same :-)

The below is my opinion , wich is formed by following a lot of these
discussions and how it is described in the manny books i own

The BIG NO NO is a bit odd , he would be right if he would have said that
it isn`t necesary and that you are typing a line to much
if your object is declared in method scope

but there are situations thinkable where it is valid to set a object to
Nothing ( however never absolut necesary , as it could have been in VB6 )

so here are some scenario`s for you to rethink :

Example A
Private sub Useobject ()
dim foo as new Objfoo.lib

---- use the foo object

--- setting the foo object here to nothing is absolute not necesary
--- as soon as it runs out of scope it is marked for collection
end sub

Example B

Private sub Useobject ()
dim foo as new Objfoo.lib

for i as integer = 0 to 1000

if i < 500 then
---- use the foo object
else
---- stop using the foo object
end if
next
end sub

--- here is a situation where it is valid to set the foo object to nothing
in the else statement ( if i = 500 then foo=Nothing )
--- especially when it is a resource hungry object , However it is not
guaranteed that the object is collected at this point
end sub

Example C
The object is declared in class scope ( because you use it withevents or
whatever reasson you might have )
and for some reasson you can live without it , for a time and if needed you
can declare a new instance
i encountered this scenario myself in a remoting scenario wich used a
singleton
if you use VB.Net 2005 then learn yourself to use the using stetement ( it
makes sure everything is nicely cleaned up , and as a bonus it makes your
code nicer readable )

example

Private sub Useobject ()
using foo as new Objfoo.lib

---- use the foo object

end using
end sub
As said the above is my own opinion without warranty`s especially about
example B i get a lot of nasty responses however it is a Balena example
written in the core reference guide of VB.net,, so i guess it should be a
valid situation .

I know this thread is going to explode ( as it normally does on this
subject ) with all people telling you something different , i would say form
your own opinion
by reading about the GC on MSDN then you will see what it does and what it
doesn`t , and especially this is verry important , setting a object to
Nothing does not mean that you will get your resources inmediatly back ,
however in resource hungry systems it might make a difference in the right
scenario .

regards

Michel Posseth [MCP]


<pa***@communit y.nospamschreef in bericht
news:eG******** ******@TK2MSFTN GP03.phx.gbl...
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 .Net also for quite a while now. The other day
one of my peers mentioned that this is a BIG NO NO and that I should let
the Garbage Collection process handle this for me.

Can someone share any insight on this?

TIA!

Oct 22 '06 #6
So forgive my ignorance here, but I am presuming VB 2005 comes with Visual
Studio 2005 and .net 2.0 framework right? What does the Using statement do?
Can I use it for both Public and Private variable declarations?
"Michel Posseth [MCP]" <MS**@posseth.c omwrote in message
news:Os******** ******@TK2MSFTN GP02.phx.gbl...
Hello ,,,

Well you have started something :-) ....... this has been discussed
manny times in this group and it always ends the same :-)

The below is my opinion , wich is formed by following a lot of these
discussions and how it is described in the manny books i own

The BIG NO NO is a bit odd , he would be right if he would have said
that it isn`t necesary and that you are typing a line to much
if your object is declared in method scope

but there are situations thinkable where it is valid to set a object to
Nothing ( however never absolut necesary , as it could have been in
VB6 )

so here are some scenario`s for you to rethink :

Example A
Private sub Useobject ()
dim foo as new Objfoo.lib

---- use the foo object

--- setting the foo object here to nothing is absolute not necesary
--- as soon as it runs out of scope it is marked for collection
end sub

Example B

Private sub Useobject ()
dim foo as new Objfoo.lib

for i as integer = 0 to 1000

if i < 500 then
---- use the foo object
else
---- stop using the foo object
end if
next
end sub

--- here is a situation where it is valid to set the foo object to nothing
in the else statement ( if i = 500 then foo=Nothing )
--- especially when it is a resource hungry object , However it is not
guaranteed that the object is collected at this point
end sub

Example C
The object is declared in class scope ( because you use it withevents or
whatever reasson you might have )
and for some reasson you can live without it , for a time and if needed
you can declare a new instance
i encountered this scenario myself in a remoting scenario wich used a
singleton
if you use VB.Net 2005 then learn yourself to use the using stetement
( it makes sure everything is nicely cleaned up , and as a bonus it makes
your code nicer readable )

example

Private sub Useobject ()
using foo as new Objfoo.lib

---- use the foo object

end using
end sub
As said the above is my own opinion without warranty`s especially about
example B i get a lot of nasty responses however it is a Balena example
written in the core reference guide of VB.net,, so i guess it should be a
valid situation .

I know this thread is going to explode ( as it normally does on this
subject ) with all people telling you something different , i would say
form your own opinion
by reading about the GC on MSDN then you will see what it does and what
it doesn`t , and especially this is verry important , setting a object to
Nothing does not mean that you will get your resources inmediatly back ,
however in resource hungry systems it might make a difference in the right
scenario .

regards

Michel Posseth [MCP]


<pa***@communit y.nospamschreef in bericht
news:eG******** ******@TK2MSFTN GP03.phx.gbl...
>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 .Net also for quite a while now. The other day
one of my peers mentioned that this is a BIG NO NO and that I should let
the Garbage Collection process handle this for me.

Can someone share any insight on this?

TIA!


Oct 22 '06 #7
Hello ,

Yes ,, VB 2005 comes with Visual Studio 2005

The using statement can only be used inside methods

The using statement guarantees , that dispose is called after exiting the
using block

Public Sub setbigbold(ByVa l c As Control)
Using nf As New System.Drawing. Font("Arial", 12.0F, _
System.Drawing. FontStyle.Bold)

c.Font = nf
c.Text = "This is 12-point Arial bold"
End Using
End Sub
for more info about the using statement
http://msdn2.microsoft.com/en-us/library/htd05whh.aspx

hth

Michel Posseth [MCP]

<pa***@communit y.nospamschreef in bericht
news:ej******** ******@TK2MSFTN GP05.phx.gbl...
So forgive my ignorance here, but I am presuming VB 2005 comes with Visual
Studio 2005 and .net 2.0 framework right? What does the Using statement
do? Can I use it for both Public and Private variable declarations?
"Michel Posseth [MCP]" <MS**@posseth.c omwrote in message
news:Os******** ******@TK2MSFTN GP02.phx.gbl...
>Hello ,,,

Well you have started something :-) ....... this has been discussed
manny times in this group and it always ends the same :-)

The below is my opinion , wich is formed by following a lot of these
discussions and how it is described in the manny books i own

The BIG NO NO is a bit odd , he would be right if he would have said
that it isn`t necesary and that you are typing a line to much
if your object is declared in method scope

but there are situations thinkable where it is valid to set a object to
Nothing ( however never absolut necesary , as it could have been in
VB6 )

so here are some scenario`s for you to rethink :

Example A
Private sub Useobject ()
dim foo as new Objfoo.lib

---- use the foo object

--- setting the foo object here to nothing is absolute not necesary
--- as soon as it runs out of scope it is marked for collection
end sub

Example B

Private sub Useobject ()
dim foo as new Objfoo.lib

for i as integer = 0 to 1000

if i < 500 then
---- use the foo object
else
---- stop using the foo object
end if
next
end sub

--- here is a situation where it is valid to set the foo object to
nothing in the else statement ( if i = 500 then foo=Nothing )
--- especially when it is a resource hungry object , However it is not
guaranteed that the object is collected at this point
end sub

Example C
The object is declared in class scope ( because you use it withevents or
whatever reasson you might have )
and for some reasson you can live without it , for a time and if needed
you can declare a new instance
i encountered this scenario myself in a remoting scenario wich used a
singleton
if you use VB.Net 2005 then learn yourself to use the using stetement (
it makes sure everything is nicely cleaned up , and as a bonus it makes
your code nicer readable )

example

Private sub Useobject ()
using foo as new Objfoo.lib

---- use the foo object

end using
end sub
As said the above is my own opinion without warranty`s especially about
example B i get a lot of nasty responses however it is a Balena example
written in the core reference guide of VB.net,, so i guess it should be a
valid situation .

I know this thread is going to explode ( as it normally does on this
subject ) with all people telling you something different , i would say
form your own opinion
by reading about the GC on MSDN then you will see what it does and what
it doesn`t , and especially this is verry important , setting a object to
Nothing does not mean that you will get your resources inmediatly back ,
however in resource hungry systems it might make a difference in the
right scenario .

regards

Michel Posseth [MCP]


<pa***@communi ty.nospamschree f in bericht
news:eG******* *******@TK2MSFT NGP03.phx.gbl.. .
>>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 .Net also for quite a while now. The other day
one of my peers mentioned that this is a BIG NO NO and that I should let
the Garbage Collection process handle this for me.

Can someone share any insight on this?

TIA!



Oct 22 '06 #8
"Michel Posseth [MCP]" <MS**@posseth.c omschrieb:
The using statement guarantees , that dispose is called after exiting the
using block

Public Sub setbigbold(ByVa l c As Control)
Using nf As New System.Drawing. Font("Arial", 12.0F, _
System.Drawing. FontStyle.Bold)

c.Font = nf
c.Text = "This is 12-point Arial bold"
End Using
End Sub
Using 'Using' is a bad idea in the sample above because the control needs an
undisposed font even after setting the font!

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Oct 22 '06 #9
Hi,

Yes, Herfried means that if the "obj" reference is a "local" variable, then
it is not necessary to set "obj" to nothing to help GC. This is because, as
a "local" variable(refere nce), "obj" will be go out of scope automatically.
So after exiting the method, it automatically has the same effect of
setting "obj" to nothing.("obj" is destroyed automatically, so it is
"nothing").

Anyway, I do not think setting "obj" to nothing is a "Big NO, NO". It will
not hurt performance much, but it is a good habit to "help" GC in certain
situation. Let's say that you have a private field of bitmap type(note, it
is not a "local" variable). If you are using this field to refer a large
bitmap, after you used it, it is a really good idea to set the field to
"nothing", this may help to tell GC that this large bitmap is not
referenced by any references, so it can be collected once the free memory
is low.

So this is not a big issue, you may continue to set all the unused
references to nothing. This may or may not help GC, but it will not hurt
performance much.

Hope this is clear.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Oct 23 '06 #10

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

Similar topics

6
1929
by: dotnettester | last post by:
Woud this work? ..... Response.end set objConn = nothing set objAnyObject = nothing ?
7
2241
by: Lucas Tam | last post by:
I'm calling the session object from an inherited page. The page is based off an herited class which outputs XML. Does anyone know why the session object would be nothing? httpcontext.current.request/response/etc all work, except for session. Thanks. --
10
1076
by: mark | last post by:
I have a windows class form2 that contains a datagrid. With Cor's help I am using this strategy to better manage memory. In form one I have: dim Matrix_A as form2 Private Sub populateA() Dim Matrix_A As New form2 Method to fill grid and display form
4
14905
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? rs.Close
10
36492
by: Alan Mailer | last post by:
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?
0
8458
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8366
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7391
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5677
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1779
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.