IDisposable

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
 
A

Arne Vajhøj

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
 
T

Tony Johansson

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
 
A

Arne Vajhøj

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top