Saturday 16 December 2017

c# - What exactly is IDisposable needed for?

itemprop="text">












I
tried to find an actual answer to my question from books, internet and on stackoverflow,
but nothing has helped me so far, so hopefully I can word my issue exact enough to make
sense.



In general I always found the same basic
usage of how to free memory, which is approx. as follows and I do understand the code
itself:



public class MyClass :
IDisposable
{
bool disposed = false;
public void
Dispose()
{
if (!disposed)

{

Dispose(true);
GC.SuppressFinalize(this);
disposed =
true;
}
}

protected virtual void
Dispose(bool disposing)
{
if (disposing)


{
//free managed ressources
}
// free other
ressources
}

~MyClass()
{

Dispose(false);

}

}


It
makes total sense the way the methods work. But now my question: Why do we need the base
class IDisposable? In this code sample we define a method called
Dispose(). As I read everywhere that method is part of
IDisposable, but we have just defined that method within
MyClass and this code would still work if we don't implement
the base class IDisposable or am I wrong with this
assumption?



I am not fully new to C# but there
is still a lot for me to learn, so hopefully someone can lead me in the right direction
here. I checked for another post with the same question, but couldn't find it, so if it
does exist and it does answer my question please lead me there and I will delete this
post.



Answer




You are right, as your destructor
~MyClass call Dispose, it seems there
is no need for the interface
IDisposable.



But
Dispose is not called only by the destructor. You can call it
yourself in the code when you want unmanaged resources to be disposed. It is needed
because you don't know when the destructor is called (it is up to the garbage
collector).




Finally,
IDisposable.Dispose is called when you use a
using.



using(MyDisposableClass
myObject = new MyDisposableClass())
{
// My
Code
}


is
equivalent
to:




MyDisposableClass
myObject = new MyDisposableClass();
try
{
// My
Code
}
finally
{

myObject.Dispose();
}



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...