PDA

View Full Version : Dispose


Suzuran
08-06-2007, 08:09 PM
// Clean up any resources being used
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}

Can anyone tell me what's the Dispose method doing? I don't really get it why do we need it. I know that it releases all the resources that it owns. But what does that actually mean? (I'm new to C#)

LE: I think I posted in the wrong place. If I'm right, can a moderator move my thread?

ess
08-06-2007, 10:01 PM
To cut a very long story short, Microsoft decided to introduce the IDisposable interface to reduce the number of try catch blocks that programmers might have to write in order to clean after opened connections...be it a network connection, or a flat file connection, database connection...among other resources.

So, if you come across any class that implements the IDisposable interface, instead of writing
try {
// some code here
}
catch(Exception e){
// handle error
}
catch(AnotherException e){
// handle error
}

you can write

using ( CLASS THAT IMPLEMENTS IDISPOSABLE HERE) {
// write code that uses the class here
}

As you can see, by using the "using block" of code, your code is shorter and much easier to read (well, depends on your view...personally, I like using try and catch...so I can catch errors and deal with them etc).

So, this prompts the question of how to use the dispose method...well, you don't have to worry about using the dispose method, unless you are writing a class that implements the IDisposable interface...and you wish to provide your class users (including yourself) the ability to use the "using" clause.

Microsoft has release a design pattern to help programmers write the dispose methods in a class that implements the IDisposable interface.

here is the url that explains how best to implement the IDisposable interface
http://msdn2.microsoft.com/en-us/library/fs2xkftw(vs.71).aspx

Note: you might need to use the language filter on MSDN website in order to see C# code, instead of VB.NET or other languages.

Hope that helps

Cheers,
Ess

Freon22
08-07-2007, 10:57 PM
Thanks ess, the C# code is shown after the vb

Thanks again