Saturday 17 August 2019

.net - What is the simplest IDisposable pattern in c#?




If I have a class which makes use of managed resources only, so I don't see any need to fully implement the IDisposable pattern.



Surely this is sufficient:



    public class ManagedResourceClient : IDisposable
{
private ITheManagedResource _myManagedResource = new TheManagedResource()


public void Dispose()
{
if ( _myManagedResource != null )
{
_myManagedResource.Dispose();
_myManagedResource = null;
}
}
}



I don't see any reason to use:




  • a finalizer as this is using only managed resources that implement IDisposable

  • a 'disposing' flag as this is handled by a null check

  • a virtual Disposing method as there is no need to differentiate between GC calls and direct calls.




Can the above be confirmed as correct?


Answer



You almost had it, because your class is not sealed someone could derive from your class and that derived class could also need to dispose a object. Make your class sealed and your current implementation is fine.



public sealed class ManagedResourceClient : IDisposable
{
private ITheManagedResource _myManagedResource = new TheManagedResource()

public void Dispose()
{

if ( _myManagedResource != null )
{
_myManagedResource.Dispose();
_myManagedResource = null;
}
}
}


If you want to learn more about disposing (and why the stock example with a finializer Microsoft gives is actually a bad example) see this really good article by Stepen Cleary: "IDisposable: What Your Mother Never Told You About Resource Deallocation"



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...