Writing our own Dispose method instead of using Idisposable
You are right, using your Release method you would get the exact same effect, provided you always remember to call it.
The reason why you should use Dispose
/ IDisposable
for this sort of thing is consistency. All .NET developers will know about the IDisposable pattern, and a class being IDisposable indicates that you should dispose of it, and do it using the Dispose method. In other words, using the IDisposable pattern immediately tells another developer, that he should release the resources held by the class, and he should do it by calling the Dispose
method.
Another benefit of implementing IDisposable
is the using block, which works on any IDisposable class:
using(var t = new Test())
{
// use t
}
Using the above code will result in t
being Dispose()
ed at the end of the using
block. It is syntactic sugar for a try
...finally
block, but it tends to make this kind of code more concise and easier to read and write.