IDisposable

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

I know what this interface is but I have never had any reason to implement
this interface because the .NET framework already implementing this
interface. So I ask if somebody can give an exampel of when it would be
suitable to implement this interface.?


//Tony
 
I know what this interface is but I have never had any reason to implement
this interface because the .NET framework already implementing this
interface. So I ask if somebody can give an exampel of when it would be
suitable to implement this interface.?

You should implement it every time you have a class that
keeps unmanaged resources (open files, open database
connections, open network connections) at the instance
level to ensure that those resources get properly released.

Arne
 
Arne Vajhøj said:
You should implement it every time you have a class that
keeps unmanaged resources (open files, open database
connections, open network connections) at the instance
level to ensure that those resources get properly released.

Arne

But .NET itself do implement this IDisposable so why should I then implemet
it in my class ?

//Tony
 
But .NET itself do implement this IDisposable so why should I then implemet
it in my class ?

Let me give an example.

public class Foo
{
public void M(string fnm)
{
using(StreamReader sr = new StreamReader(fnm))
{
// read lines and do something with them
}
}
}

here you use the fact that StreamReader implements
IDisposable and you don't need to implement it.

public class Bar
{
private StreamReader sr;
public Bar(string fnm)
{
sr = new StreamReader(fnm))
}
public M1()
{
// do something with sr
}
public M2()
{
// do something with sr
}
}

here you can not use the fact that StreamReader implements
IDisposable.

And you should write it as:

public class Bar : IDisposable

(and let Dispose handle sr).

Arne
 
Back
Top