How to deal with unintentional resources in case of extension class?

There are two classes ClassA and ClassB. ClassB extends ClassA. There are unmanaged resources in ClassA as well as ClassB. So the question is: should the Dispose () method be provided for both of these classes or will Dispose for ClassA be enough

Edit1: In the answer I received so far, I think my statement was misunderstood, since ClassB inherits from ClassA. What I had in mind can be understood by visiting the following links:

+4
source share
2 answers

Dispose . Dispose B . , # ( , ).

// Class B

public void Dispose()
{
    base.Dispose();

    // Dispose the rest (unmanaged B)
}
+3

, ClassB . , ClassA Dispose ClassB. ClassA

// In ClassA

public void Dispose()
{
    Dispose(true);

    // Only if you are using a finalizer
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        // get rid of managed resources
    }   
    // get rid of unmanaged resources
}

ClassB Dispose(bool disposing) IDisposable.

// In ClassB

protected override void Dispose(bool disposing)
{
    base.Dispose(disposing);
    if (disposing)
    {
        // get rid of managed resources declared in ClassB
    }   
    // get rid of unmanaged resources declared in ClassB
}

Dispose(false);.

0

Source: https://habr.com/ru/post/1530765/


All Articles