473,396 Members | 1,923 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,396 software developers and data experts.

IDisposable or not in custom classes

Hi,

Following on from the recent thread about why HttpWebRequest doesn't
implement the IDisposable interface, I got to wondering whether people make
their custom classes inherit IDisposable or not as a general rule, or only
under certain circumstances...

Since it's an easy enough thing to do
(http://msdn2.microsoft.com/en-us/lib...sposable.aspx), is there
any good reason not to make every custom class IDisposable, the same way as
there's no good reason not to use exception handling in every method...?

I can understand the rationale for implementing IDisposable for classes
which e.g. use unmanaged resources, or which open files and/or streams,
because the GC won't know about them, but what about for classes which use /
reference only managed code? Would it be overkill to make those classes
IDisposable, and would it simply be enough to destroy references to them by
variables which have instantiated them to null...?

Interested to know your opinions...

Mark
Dec 13 '06 #1
11 2284
Hi Mark,
Following on from the recent thread about why HttpWebRequest doesn't
implement the IDisposable interface, I got to wondering whether people
make their custom classes inherit IDisposable or not as a general rule, or
only under certain circumstances...
IDisposable should be implemented if your class composites:

A. unmanaged resources
B. IDisposable types

If your class doesn't manage the lifetime of unmanaged or IDisposable
references then IDisposable isn't necessary. In all other circumstances,
IDisposable isn't necessary either.
Since it's an easy enough thing to do
(http://msdn2.microsoft.com/en-us/lib...sposable.aspx), is
there any good reason not to make every custom class IDisposable, the same
way as there's no good reason not to use exception handling in every
method...?
I strongly disagree that exception handling should be placed in every
method:

http://davesexton.com/cs/blogs/blog/...ntingency.aspx
I can understand the rationale for implementing IDisposable for classes
which e.g. use unmanaged resources, or which open files and/or streams,
because the GC won't know about them, but what about for classes which use
/ reference only managed code? Would it be overkill to make those classes
IDisposable, and would it simply be enough to destroy references to them
by variables which have instantiated them to null...?
Overkill :)

--
Dave Sexton
Dec 13 '06 #2
I can understand the rationale for implementing IDisposable for
classes which e.g. use unmanaged resources, or which open files and/or
streams, because the GC won't know about them, but what about for
classes which use / reference only managed code? Would it be overkill
to make those classes IDisposable, and would it simply be enough to
destroy references to them by variables which have instantiated them
to null...?
This is most certaily overkill. IMO, it betrays a mistrust of the garbage
collector.

Best Regards,
Dustin Campbell
Developer Express Inc.
Dec 13 '06 #3
Mark,

You've received some good comments already. Let me go a different
direction. I think there are times where implementing IDisposable
makes since even if the class does not hold unmanaged resources or
managed types that implement IDisposable. Candidates include anything
with Acquire/Release, Open/Close, Enter/Exit, etc. semantics.

Jon Skeet provides the best example of this. By wrapping the Monitor
in a IDisposable object you can take advantage of the using construct
instead of lock. The wrapping class would not comply with the
canonical rules for IDisposable implementation. Nevertheless, I think
it is acceptable.

http://www.yoda.arachsys.com/csharp/...e/locking.html

P.S. Too bad Microsoft didn't take full advantage of "using". It could
have prevented the addition of another keyword (namely "lock").

Brian

Mark Rae wrote:
Hi,

Following on from the recent thread about why HttpWebRequest doesn't
implement the IDisposable interface, I got to wondering whether people make
their custom classes inherit IDisposable or not as a general rule, or only
under certain circumstances...

Since it's an easy enough thing to do
(http://msdn2.microsoft.com/en-us/lib...sposable.aspx), is there
any good reason not to make every custom class IDisposable, the same way as
there's no good reason not to use exception handling in every method...?

I can understand the rationale for implementing IDisposable for classes
which e.g. use unmanaged resources, or which open files and/or streams,
because the GC won't know about them, but what about for classes which use /
reference only managed code? Would it be overkill to make those classes
IDisposable, and would it simply be enough to destroy references to them by
variables which have instantiated them to null...?

Interested to know your opinions...

Mark
Dec 13 '06 #4
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uY**************@TK2MSFTNGP06.phx.gbl...

Dave,
IDisposable should be implemented if your class composites:

A. unmanaged resources
B. IDisposable types

If your class doesn't manage the lifetime of unmanaged or IDisposable
references then IDisposable isn't necessary. In all other circumstances,
IDisposable isn't necessary either.
OK - that makes sense.

Related to this, am I right in thinking that if you instantiate a custom
class which implements IDisposable with the using (...) syntax, the class
*needs* to have a .Dispose() method? I.e. when the code encapsulated by
using (...) exists, does it look for a Dispose() method in the class which
it instantiated, or does it dispose of it in some other way...?

Mark
Dec 13 '06 #5
Mark,

Can you show the thread that you are referring to? I don't know if it
was pointed out, but there is no reason to implement IDisposable on the
request since the request doesn't do anything until it is sent. The
WebRequest model basically places the managability of the unmanaged stuff in
the Response (which you are going to get most likely because you made the
request in the first place) and then call Dispose of it there.

And yes, it is overkill to implement it on all the classes. There are
very specific guidelines in place for when to implement IDisposable.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mark Rae" <ma**@markNOSPAMrae.comwrote in message
news:eq**************@TK2MSFTNGP03.phx.gbl...
Hi,

Following on from the recent thread about why HttpWebRequest doesn't
implement the IDisposable interface, I got to wondering whether people
make their custom classes inherit IDisposable or not as a general rule, or
only under certain circumstances...

Since it's an easy enough thing to do
(http://msdn2.microsoft.com/en-us/lib...sposable.aspx), is
there any good reason not to make every custom class IDisposable, the same
way as there's no good reason not to use exception handling in every
method...?

I can understand the rationale for implementing IDisposable for classes
which e.g. use unmanaged resources, or which open files and/or streams,
because the GC won't know about them, but what about for classes which use
/ reference only managed code? Would it be overkill to make those classes
IDisposable, and would it simply be enough to destroy references to them
by variables which have instantiated them to null...?

Interested to know your opinions...

Mark

Dec 13 '06 #6
"Mark R. Dawson" <Ma*********@discussions.microsoft.comwrote in message
news:DF**********************************@microsof t.com...
If you have the class implementing the IDisposable interface then it must
have a Dispose() method since that is part of the interface.
D'oh! I really could have found that out for myself...Apologies.

I'm learning a lot of good practices here, though...

OK, here's another one...

Let's say you have a Database Abstraction Layer class called MyDAL which,
for the sake of argument, has a static method called GetSqlDataReader which
accepts a string of SQL as its only argument and returns an SqlDataReader
object). Barring the obvious comments about using stored procedures to avoid
SQL Injection, it might look something like this:

public static SqlDataReader GetSqlDataReader(string strSQL)
{
try
{
using (SqlConnection objSqlConn = new SqlConnection(<read connection
string from config file>))
{
using (SqlCommand objSqlCommand = new SqlCommand(strSQL,
objSqlConn))
{
objSqlCommand.Connection.Open();
return
(objSqlCommand.ExecuteReader(CommandBehavior.Close Connection));
}
}
}
catch (SqlException ex)
{
throw ex;
}
catch(Exception)
{
throw;
}
}

You might use it something like this:

using (SqlDataReader objDR = MyDAL.GetSqlDataReader("SELECT * FROM
MyTable"))
{
while (objDR.Read())
{
// do something
}
objDR.Close(); // is this necessary?
}

Since SqlDataReader is disposable, and it has been instantiated with the
using (...) syntax, and the reader itself has been created with the
ExecuteReader method of a SqlCommand object specifying the
CommandBehavior.CloseConnection property), is the line "objDR.Close()"
necessary...?
Dec 13 '06 #7
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote in
message news:%2****************@TK2MSFTNGP04.phx.gbl...

Nicholas,
Can you show the thread that you are referring to?
Its subject is "HttpWebRequest and IDisposable" and it was started by me in
this group on 10th December.
I don't know if it was pointed out, but there is no reason to implement
IDisposable on the request since the request doesn't do anything until it
is sent.
It's actually not possible to implement it because it's not disposable, much
to everyone's surprise...
And yes, it is overkill to implement it on all the classes.
Indeed.
There are very specific guidelines in place for when to implement
IDisposable.
Are there? Are they available for download anywhere...?

Mark
Dec 13 '06 #8

Close() is not necessary when using "using".

Also note that since your class is returning a connected Reader
instance you do not want to use "using" on the SqlConnection object
'cause you don't want to close the connection. That's why readers
have the CloseConnection behavior, you don't have to worry about
closing the connection 'cause the reader closes it automatically when
the reader itself is closed.

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
On Wed, 13 Dec 2006 19:07:18 -0000, "Mark Rae"
<ma**@markNOSPAMrae.comwrote:
>"Mark R. Dawson" <Ma*********@discussions.microsoft.comwrote in message
news:DF**********************************@microso ft.com...
>If you have the class implementing the IDisposable interface then it must
have a Dispose() method since that is part of the interface.

D'oh! I really could have found that out for myself...Apologies.

I'm learning a lot of good practices here, though...

OK, here's another one...

Let's say you have a Database Abstraction Layer class called MyDAL which,
for the sake of argument, has a static method called GetSqlDataReader which
accepts a string of SQL as its only argument and returns an SqlDataReader
object). Barring the obvious comments about using stored procedures to avoid
SQL Injection, it might look something like this:

public static SqlDataReader GetSqlDataReader(string strSQL)
{
try
{
using (SqlConnection objSqlConn = new SqlConnection(<read connection
string from config file>))
{
using (SqlCommand objSqlCommand = new SqlCommand(strSQL,
objSqlConn))
{
objSqlCommand.Connection.Open();
return
(objSqlCommand.ExecuteReader(CommandBehavior.Clos eConnection));
}
}
}
catch (SqlException ex)
{
throw ex;
}
catch(Exception)
{
throw;
}
}

You might use it something like this:

using (SqlDataReader objDR = MyDAL.GetSqlDataReader("SELECT * FROM
MyTable"))
{
while (objDR.Read())
{
// do something
}
objDR.Close(); // is this necessary?
}

Since SqlDataReader is disposable, and it has been instantiated with the
using (...) syntax, and the reader itself has been created with the
ExecuteReader method of a SqlCommand object specifying the
CommandBehavior.CloseConnection property), is the line "objDR.Close()"
necessary...?
Dec 13 '06 #9
"Samuel R. Neff" <sa********@nomail.comwrote in message
news:83********************************@4ax.com...
Close() is not necessary when using "using".
OK.
Also note that since your class is returning a connected Reader
instance you do not want to use "using" on the SqlConnection object
'cause you don't want to close the connection. That's why readers
have the CloseConnection behavior, you don't have to worry about
closing the connection 'cause the reader closes it automatically when
the reader itself is closed.
Thanks very much.
Dec 14 '06 #10
Hi Mark,
>There are very specific guidelines in place for when to implement
IDisposable.

Are there? Are they available for download anywhere...?
".NET Framework Developer's Guide, Implementing Finalize and Dispose to
Clean Up Unmanaged Resources"
http://msdn2.microsoft.com/en-us/library/b1yfkh5e.aspx

".NET Framework Developer's Guide, Implementing a Dispose Method"
http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx

Check out the TOC on the left and you'll see a whole bunch of topics that
provide development guidelines for many other things.

Note that the guidelines recommending to use Dispose along with a finalizer
can be accomplished easily by deriving your class from Component, which
provides the recommended behavior already; however, that certainly doesn't
mean you should derive all of your classes from Component just like you
shouldn't implement IDisposable on all of your classes either. Deriving
from Component also provides base designer support for your business objects
so they can be added to the component tray from the toolbox, a protected
EventHandlerList used by derived Controls, and a Container/Site pattern
implementation for designers, which may be useful to you in and of itself.

Realize too that you don't need to have a finalizer on your classes (that
don't derive from Component) if they simply aggregate or composite
references to IDisposables since each IDisposable reference should have
already implemented their own finalization code to release the unmanaged
resources.

--
Dave Sexton

"Mark Rae" <ma**@markNOSPAMrae.comwrote in message
news:Ol**************@TK2MSFTNGP04.phx.gbl...
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote
in message news:%2****************@TK2MSFTNGP04.phx.gbl...

Nicholas,
>Can you show the thread that you are referring to?

Its subject is "HttpWebRequest and IDisposable" and it was started by me
in this group on 10th December.
>I don't know if it was pointed out, but there is no reason to implement
IDisposable on the request since the request doesn't do anything until it
is sent.

It's actually not possible to implement it because it's not disposable,
much to everyone's surprise...
>And yes, it is overkill to implement it on all the classes.

Indeed.
>There are very specific guidelines in place for when to implement
IDisposable.

Are there? Are they available for download anywhere...?

Mark

Dec 14 '06 #11
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:es**************@TK2MSFTNGP03.phx.gbl...
>>There are very specific guidelines in place for when to implement
IDisposable.

Are there? Are they available for download anywhere...?

".NET Framework Developer's Guide, Implementing Finalize and Dispose to
Clean Up Unmanaged Resources"
http://msdn2.microsoft.com/en-us/library/b1yfkh5e.aspx

".NET Framework Developer's Guide, Implementing a Dispose Method"
http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx

Check out the TOC on the left and you'll see a whole bunch of topics that
provide development guidelines for many other things.
Got a bit of reading to do, then...:-)

Thanks very much.
Dec 14 '06 #12

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

Similar topics

1
by: glenn | last post by:
I have written as a test a customer class that has all the necessary field handling and formatting routines in it that I need. I have dataaccess class that controls reading and writing the class...
0
by: Brett | last post by:
I am working with vb.net in a asp.net application. I have created a config file in xml format. The goal is to be able to change the config file without having to recompile the entire...
6
by: Scott Mueller | last post by:
I have a question about simple binding: (please forgive any syntax errors... I am at home, where I do not have Vb.Net installed, and I rely far too much on Vb's intellisense!) If I have two...
0
by: SMFX | last post by:
Okay, this should be a simple thing, but I can't seemto find the right documentation on it. I created a custom class that inherits from a well known class. For example: Class MyString Inherits...
27
by: Keith Wilby | last post by:
I've been trying to get my head around custom classes by following the example in the Visual Basic Language Developer's Handbook by Sybex. I think I have a handle on what they're about, albeit a...
2
by: Paul Hadfield | last post by:
Hi, I'm not having a lot of luck googling for this one, I want to be able to store a custom class in the user settings (DotNet2.0, win app). I don't wish to create public get / set properities...
0
by: Crazy Cat | last post by:
HI I'm developing a desktop application in Visual Studio 2005 Professional and need help. I've created several custom classes for my project but they appear invisible to my forms!!! For...
1
by: realfantasy | last post by:
hi guys i have a problem regarding asp.net/vb.net, normally we make utility classes or any custom classes and put them in app_code folder but i need to put those class files outside of app_code...
0
by: J. Cliff Dyer | last post by:
On Wed, 2008-04-30 at 11:02 -0500, Victor Subervi wrote: Victor, Once again, you've posted code that doesn't work. Your outer try block is never terminated, and w is never initialized (so...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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,...

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.