473,888 Members | 2,194 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple question about dispose() and = null

Hi,

I have come across codes like this

if(dbConn != null)
{
dbConn.dispose( );
}

and sometimes like

dbConn.dispose( );

if(dbConn != null)
{
dbConn = null;
}

I was wondering what is the correct way of cleaning up?

Thanks

Joey
Nov 16 '05 #1
4 2009
Joey wrote:
I was wondering what is the correct way of cleaning up?

Class instances often encapsulate control over resources that are not
managed by the runtime, such as database connections and similar. You
can provide implicit control over how these resources are managed by
implementing a destructor in the class. The garbage collector calls this
method at some point after there are no longer any valid references to
the object.

If an external resource is scarce or expensive, you might want to
provide the ability to explicitly release these resources before the
garbage collector frees the object. To provide explicit control,
implement the IDisposable interface.

If you implement IDisposable, you should provide implicit cleanup using
a destructor.

Here is an example of a best-practice implementation of IDisposable:
public class MyClass : IDisposable {
public void Dispose() {
Dispose(true);
GC.SuppressFina lize(this);
}

protected virtual void Dispose(bool disposing) {
if (disposing) {
// Free other managed objects.
}
// Free unmanaged objects and set large fields to null.
}

~MyClass() {
Dispose (false);
}
}

For more info on when you use destructors and when to implement the
IDisposable interface see
http://msdn.microsoft.com/library/de...izeDispose.asp

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 16 '05 #2
Hi, Joey!

class MyDisposableCla ss : IDisposable
{

private SqlConnection _connection;
....

public void Dispose()
{
this.Dispose( true );
GC.SuppressFina lize( this );
}

private void DisposeConnecti on()
{
if ( _connection == null ) return;
_connection.Dis pose();
_connection = null;
}

protected virtual void Dispose( bool disposing )
{
if ( disposing ){
DisposeConnecti on();
}
}

~MyDisposableCl ass()
{
this.Dispose( false );
}

}

--
WBR, Roman S. Golubin
ICQ UIN: 63253392

Nov 16 '05 #3
Anders Norås <an**********@o bjectware.no> wrote:

<snip>
If you implement IDisposable, you should provide implicit cleanup using
a destructor.


That's not always true. If you implement IDisposable in order to call
Dispose on other objects, there's usually no need for a destructor.

If you contain unmanaged resources directly, *that's* the place for a
destructor.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
dbConn.dispose( );

if(dbConn != null)
{
dbConn = null;
}


This code is malformed. There is no point checking to see whether dbConn
is null after calling Dispose. If dbConn is null, then the Dispose call
is going to raise a null pointer exception. Dispose itself is not going
to set the dbConn variable to null.

The other code example made sense. Or you could do this:

if(dbConn != null)
{
dbConn.Dispose( );
dbConn = null;
}

The if statement isn't necessary if you can find a way to employ a using
statement.

H^2
Nov 16 '05 #5

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

Similar topics

3
6095
by: faktujaa | last post by:
Hi All, A small confusion. I have defined a connection class that has System.Data.IDbConnection as a member variable and implements IDisposable interface. I have implemented Dispose method to call Dispose method of IDbConnection. This Dispose method is called from a destructor. In the dispose method, i also call GC.SuppressFinalize(this) so as to avoid finalizer. All this was OK untill i came across one article that says - not to call...
4
2041
by: xyu | last post by:
Hello, First I would like to thank anyone who helps me, much appreciated. I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off the heap and release the memory when it's deleted from the hash table so that GC recollection does not need to run that frequently. I read up examples about Dispose method in MSDN. What I find very strange is that it's all talking about how to...
0
7577
by: Tal Sharfi | last post by:
Hi everyone I recently had the need for StringGrid object same as the one that Delphi has. An object that helps show lists of other objects in a simple grid. I searched the news groups and found none, so, I wrote one and decided to share it with you. It's a very simple one with few functions. I derived a DataGrid and added to it a DataTable to hold the data. The object itself is handling the synchronization between them, because...
2
2002
by: afatdog | last post by:
Form1: //----------------------------------------------------------------- public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.ComponentModel.IContainer components = null; public Form1() { // This call is required by the Windows Form Designer.
0
1225
by: afatdog | last post by:
Form1: //----------------------------------------------------------------- public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.ComponentModel.IContainer components = null; public Form1() { // This call is required by the Windows Form Designer.
0
413
by: Robert Ludig | last post by:
How do I bind a textbox to a simple string varaible with databinding? I managed to do the binding but unfortnatedly the textvox does not get updated when I change the string wich the textbox is bound to. I though this automation is on of the purposes of the databinding ... ? What am I doing wrong ? See this little example code: using System;
12
4427
by: Jeff B. | last post by:
If an object implements the IDisposable interface, should I always call the Dispose method or is just setting it to null and letting the GC handle it sufficient? Here is the pattern I've been using but wasn't sure if it was necessary: DataAdapter da = null; try { // Some logic here... } catch (Exception ex) {
1
1774
by: Chris Dunaway | last post by:
I have created a simple Extender Provider and when I drop it onto a form, it appears in the component tray, but none of the controls it is supposed to provide a property for show the property in the PropertyGrid! Here is the class. The GlassButton is a custom button control that derives from button and I just do some custom painting. I am sure I have just omitted something simple, but I cannot see it. I am using VS 2005.
10
1398
by: Nemisis | last post by:
HI everyone, I think i am on the right path but if someone could confirm it, that would be great. In my business Layer i have my business object, for this example, called User. User has about 50 properties.
0
9799
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
10772
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
9593
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...
0
7143
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();...
0
5810
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4635
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
4239
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3245
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.