You should release allocated resouces (IDisposable
instances). In your case it is MyParentClass
who allocates, that's why
it should Dispose
it:
public class MyParentClass {
// Let it be a property - user is not supposed to assign value here
public List<string>.Enumerator MyEnumerator {get; private set;} =
new List<string>.Enumerator();
// Here we dispose allocated resources
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (MyEnumerator is not null)
MyEnumerator.Dispose();
MyEnumerator = null;
}
}
// IDisposable interface implementation
public Dispose() => Dispose(true);
}
When you implement derived class you don't have to do anything, since MyParentClass
provides all required code:
public class MyDerivedClass : MyParentClass {
}
If MyNextDerivedClass
has anything to dispose, just override Dispose
and add required code:
public class MyNextDerivedClass : MyParentClass {
public List<string>.Enumerator MyOtherEnumerator {get; private set;} =
new List<string>.Enumerator();
protected override void Dispose(bool disposing) {
// dispose MyParentClass resource
base.Dispose(bool);
// extra code to dispose MyNextDerivedClass own resources
if (disposing) {
if (MyOtherEnumerator is not null)
MyOtherEnumerator.Dispose();
MyOtherEnumerator = null;
}
}
}