Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing objects (simplification)

I found this code in Mono reimplementation of cryptographic transforms.

I didn't modify or simplify anything - this is how it actually goes (there are comments like // Dispose unmanaged objects, but nothing is actually done).

Now - the IDisposable-related code seems redundant to me. Can this somehow be simplified / removed completely without breaking something important?

public class ToBase64Transform : ICryptoTransform
{
    private bool disposed;

    ~ToBase64Transform()
    {
        Dispose(false);
    }

    public void Clear()
    {
        Dispose(true);
    }

    void IDisposable.Dispose()
    {
        Dispose(true);
        // Finalization is now unnecessary.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed) return;

        if (disposing)
        {
        }

        disposed = true;
    }

Full source is located here.

like image 255
Yippie-Ki-Yay Avatar asked Aug 20 '26 14:08

Yippie-Ki-Yay


1 Answers

If it wraps unmanaged components, then that is the most appropriate implemntation.

If there aren't any unmanaged components, and it won't be subclassed, then yes; you can remove the finalizer and make it just have a simple Dispose():

public sealed class ToBase64Transform : ICryptoTransform
{
    private bool disposed;

    public void Dispose()
    {
        if (disposed) return;
        // Dispose managed objects
        disposed = true;
    }

If there aren't any managed disposable components either, then ... just don't make it implement IDisposable.

I'm not sure I would expect a "Clear()" method to call "Dispose()", but maybe that is the norm in the context of crypto-streams.

like image 189
Marc Gravell Avatar answered Aug 23 '26 04:08

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!