I don't think this question has been asked before but I'm a bit confused on the best way to implement IDisposable on a sealed class - more particularly a sealed class that does not inherit from a base class ( i.e a 'pure sealed class' which is my made up term ).
Dunno about you but I find the guidelines on implementing IDisposable very confusing - however what I want to know is if this would be sufficient and safe
I'm doing some P/Invoke code that allocates an IntPtr
through Marshal.AllocHGlobal
and naturally, I want to cleanly dispose of the unmanaged memory I've created. So I'm thinking of something like this
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public sealed class MemBlock : IDisposable
{
IntPtr ptr;
int length;
MemBlock(int size)
{
ptr = Marshal.AllocHGlobal(size);
length = size;
}
public void Dispose()
{
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
ptr = IntPtr.Zero;
GC.SuppressFinalize(this);
}
}
~MemBlock()
{
Dispose();
}
}
I'm assuming that because MemBlock is completely sealed and never derives from another class that implementing a virtual protected Dispose(bool disposing)
is not necessary.
Also, is the finalizer strictly necessary?
All thoughts welcome