I am currently trying to override the Remove function of the generic List-Class. But I am struggling with one tiny part of my approach - with the reference to an object outside of the Remove-method.
public new void Remove(ref string item)
{
if (Count > 9)
{
Remove(this[0]);
}
base.Remove(item);
}
This method doesnt work because it is not overriding the actual Remove-method.
Does anyone know how to handle this?
EDIT: in the remove function I want to call a method on the reference object.
EDIT2: my current version
class SocketList<WebSocketConnection>
{
private List<WebSocketConnection> theList = new List<WebSocketConnection>();
public void Remove(ref WebSocketConnection obj)
{
obj.Dispose();
theList.Remove(obj);
// additional stuff
}
}
But in this version it is not possible to call the Dispose method on the referenced object. Im getting a message that says that there is no such method available for this object.
EDIT3: This is the Class in which I want to call the Dispose method
public class WebSocketConnection : IWebSocketConnection
{
{...}
// Flag: Has Dispose already been called?
private bool disposed = false;
// Instantiate a SafeHandle instance.
private SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
{...}
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
You can´t override any member of List<T> because non of them is virtual. Also new won´t solve this because it simply hides the base-implementation. You may your list as MyExtList<MyClass> a = new MyExtList<MyClass>(). However whenever you cast this instance to its base-class also the base-implementation is used instead of your "overridden" one.
However you can do the following to achieve what you really want:
class MyExtList<T>
{
private List<T> theList = new List<T>();
public void Remove(T obj)
{
theList.Remove(obj)
// additional stuff
}
}
Thuse you won´t even need inheritance of List<T> but use a compoisition which gives you much more flexibility on what you offer to the user of your class. With your current implementation the user could do everything with the list what he could do with the generic List-implementation also. However in most situation you´re just interested in providing a few methods instead of all. So you can nicely hide everything you won´t provide to the outside by making a completely new class that uses List<T> instead of deriving from it.
Related
I work on a huge project in C# .NET 4.0. There is a custom class inherited from System.Net.Sockets.SocketAsyncEventArgs class. Something like the following:
public class SocketTaskArgs : SocketAsyncEventArgs
{
public SocketTaskArgs()
{
Completed += someEventhHandler;
}
public void CleanUp()
{
Completed -= someEventhHandler;
}
/*
There is a lot of code here that is unimportant at the moment.
*/
}
So, I wanted to move the content of CleanUp() method to Dispose(bool) method.
As first, I checked the source code of the base class - SocketAsyncEventArgs (using Go To Definition so that I saw metadata as source). I found out, this class implements IDisposable interface. Nice, I just need to override the Dispose(bool) method, don't I? (See IDisposable Interface on MSDN, the "IDisposable and the inheritance hierarchy" section, for more details). Nothing new for me... Unfortunately, the SocketAsyncEventArgs class is implemented as following:
public class SocketAsyncEventArgs : EventArgs, IDisposable
{
public void Dispose();
//some other stuff here
}
That means, there is no way how to override Dispose(bool) method, as it's implemented as private instead of protected... What is the reason for this?
Next, I read about SocketAsyncEventArgs.Dispose() method on MSDN. The funny thing is that, it contains the following section:
Notes to Inheritors
Dispose can be called multiple times by other
objects. When overriding Dispose(Boolean), be careful not to reference
objects that have been previously disposed of in an earlier call to
Dispose. For more information about how to implement Dispose(Boolean),
see Implementing a Dispose Method.
Wait... what?
When overriding Dispose(Boolean), ...
How am I supposed to override Dispose(Boolean)?
What is the recommended way to implement IDisposable interface in this case?
There doesn't seem to be anything stopping you from implementing IDisposable on your child class, take this example:
public class DisposableParent : IDisposable
{
public void Dispose()
{
Console.WriteLine("The parent was disposed.");
}
}
public class DisposableChild : DisposableParent, IDisposable
{
public new void Dispose()
{
base.Dispose();
Console.WriteLine("The child was disposed.");
}
}
public class Program
{
public static void Main()
{
using (DisposableChild c = new DisposableChild()) { }
Console.ReadKey(true);
}
}
Gives the following output:
The parent was disposed.
The child was disposed.
The compiler warns about hiding the dispose of the parent class in the child, so using the new operator gets rid of that warning, just make sure to call the base class Dispose from the child class (and implement it the right way).
The dispose for the child would become something like:
public class DisposableChild : DisposableParent, IDisposable
{
private bool _disposed = false;
public new void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_disposed)
{
base.Dispose();
Console.WriteLine("The child was disposed.");
_disposed = true;
}
}
}
}
And yes, this still works if you do something like:
using (DisposableParent p = new DisposableChild())
{
}
But something like this can break it:
public class Program
{
public static void Main()
{
DisposableChild c = new DisposableChild();
DisposeOfIt(c);
Console.ReadKey(true);
}
public static void DisposeOfIt(DisposableParent p)
{
p.Dispose();
}
}
Only prints out that the parent was disposed. So if you used this method you would have to be careful about controlling the lifetime of your objects.
I have written the following class:
public class CoupleFrames
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
}
Now I'm using the following code for disposing the variables.
CoupleFrames cf = new CoupleFrames(frame1, frame2);
// some code...
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();
I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?
I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?
Sure - you should make CoupleFrames implement IDisposable, and its Dispose method should dispose of the objects it "owns". For example:
public sealed class CoupleFrames : IDisposable
{
private readonly ColorImageFrame colorFrame;
private readonly Bitmap desktopFrame;
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
// TODO: Argument validation, unless it's valid for these parameters
// to be null, in which case the Dispose method would need to be careful.
this.colorFrame = cif;
this.desktopFrame = df;
}
public void Dispose()
{
colorFrame.Dispose();
desktopFrame.Dispose();
}
}
A few points to note:
You should make sure it's clear that the CoupleFrame really "owns" these constituent objects. Disposal relies on a clear ownership model
If CoupleFrame isn't sealed (and can't be) you may need to go into a more complicated pattern with virtual methods and finalizers. It can get very complicated, and you should read the advice given here by Joe Duffy et al. If your class is sealed, a lot of that complexity goes away
Public fields are generally a bad idea (in terms of encapsulation), which is why I've made them private here. I've also made them readonly, as if they can be changed later you need to think about whether changing them should dispose of the previously-referenced object etc.
By making CoupleFrame implement IDisposable, you're basically telling all clients that they should dispose of any instance they own. If you're not happy with imposing that burden, you need to rethink the design a bit.
I would implement the Dispose pattern
public class CoupleFrames : IDisposable
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
colorFrame.Dispose();
desktopFrame.Dispose();
}
disposed = true;
}
}
You can use the IDisposable interface.
public class CoupleFrames : IDisposable
{
....
public void Dispose()
{
// Your disposing code here
}
~CoupleFrames()
{
Dispose();
}
}
You can use the destructor to call the Dispose method since the object can sometimes be deleted by the GC.
Make CoupleFrames Implement the Idisposable Interface.
public class CoupleFrames : IDisposable
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}
public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
public void Dispose()
{
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();
}
Forgive me in advance if this question is a little too open-ended, but I've seen similar language discussion posts here so I figured I'd take the plunge.
Anyway, I have read several MSDN help pages and various other blogs on the subject of properly implementing IDisposable classes. I feel like I understand things pretty well, but I have to wonder if there's a flaw in the suggested class structure:
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!mDisposed)
{
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
}
Anytime the above is supposed to serve as a base class, you rely on the implementer of the subclass to properly override the Dispose(bool) method where necessary. In short, derived classes must ensure they invoke the base Dispose(bool) method from within their overridden version. If not, the base class' unmanaged resources may never get freed, defeating the primary purpose of the IDisposable interface.
We all know the benefits of virtual methods, but it seems like in this case their design falls short. In fact, I think this particular shortcoming of virtual methods manifests itself frequently when trying to design visual components and similar base/derived class structures.
Consider the following change, using a protected event rather than a protected virtual method:
public class DisposeEventArgs : EventArgs
{
public bool Disposing { get; protected set; }
public DisposeEventArgs(bool disposing)
{
Disposing = disposing;
}
}
public class DisposableBase : IDisposable
{
private bool mDisposed;
protected event EventHandler<DisposeEventArgs> Disposing;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// This method is now private rather than protected virtual
private void Dispose(bool disposing)
{
if (!mDisposed)
{
// Allow subclasses to react to disposing event
AtDisposing(new DisposeEventArgs(disposing));
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
private void AtDisposing(DisposeEventArgs args)
{
try
{
EventHandler<DisposeEventArgs> handler = Disposing;
if (handler != null) handler(this, args);
}
catch
{
}
}
}
With this design, the base class' Dispose(bool) method will always be called, regardless of whether subclasses subscribe to the Disposing event or not. The biggest flaw that I can see with this revised setup is that there is no predetermined order for when event listeners are called. This could be problematic if there are multiple levels of inheritance, e.g. SubclassA's listener might be triggered before its child SubclassB's listener. Is this flaw serious enough to invalidate my revised design?
This design dilemma makes me wish there were some sort of modifier for methods that was similar to virtual but which would ensure that the base class' method was always called, even if a subclass overrode that function. If there's a better way to achieve this, I would greatly appreciate your suggestions.
You're using an event here when really you want to use an inheritance mechanism like virtual. For scenarios like this where I want to ensure my implementation is always called but want to allow for base class customization I use the following pattern
private void Dispose(bool disposing)
if (mDisposed) {
return;
}
if (disposing) {
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
DisposeCore(disposing);
}
protected virtual void DisposeCore(bool disposing) {
// Do nothing by default
}
With this pattern I've ensured my base class Dispose implementation will always be called. Derived classes can't stop me by simply forgetting to call a base method. They can still opt into the dispose pattern by overriding DisposeCore but they can't break the base class contract.
The derived class can simply re-implement IDisposable and thus prevent your dispose method from being called, so you can't ensure that either.
Personally I wouldn't use either pattern. I prefer building on SafeHandle and similar mechanisms, instead of implementing finalizers myself.
Consider making it apparent that Dispose is not being called so someone will catch it. Of course Debug.WriteLine will only be called when the code is compiled with DEBUG compiler directive defined.
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
if (!mDisposed)
System.Diagnostics.Debug.WriteLine ("Object not disposed: " + this + "(" + GetHashCode() + ")";
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
You can break it down:
A destructor (finalizer) is only needed for unmanaged resources.
Using a Safehandle can turn an unmanged resource into a managed resource.
Ergo: You won't need a destructor. That halves the Dispose pattern.
The reference design uses a virtual void Dispose(bool) to cater for the Base/Derived class problem. This puts the burden on the derived class to call base.Dispose(disposing), the core of your question. I use 2 approaches:
1) Prevent it. With a sealed base-class you won't have to worry.
sealed class Foo:IDisposable
{
void Dispose() { _member.Dispose(); }
}
2) Check it. Like #j-agent's answer but conditional. When performance could be an issue then you don't want the finalizers in Production code:
class Foo:IDisposable
{
void Dispose() { Dispose(true); }
[Conditional("TEST")] // or "DEBUG"
~Foo { throw new InvalidOperation("somebody forgot to Dispose") }
}
The destructor is going to be called no matter if any subclass overrides Dispose() (can be via override or new) but your destructor is going to be called ( ~DisposableBase() ) so i bet putting your logic for cleanup there can be a good starting point.
Here is an intersting article about destructors: http://www.c-sharpcorner.com/UploadFile/chandrahundigam/UnderstandingDestructors11192005021208AM/UnderstandingDestructors.aspx
I am using Quartz.NET in an application. What is the proper way to dispose of Quartz.NET.
Right now I am just doing
if (_quartzScheduler != null)
{
_quartzScheduler = null;
}
Is that enough or should I implement a dispose or something in the jobType class?
Seth
scheduler.Shutdown(waitForJobsToComplete: true);
Of course, if you're not on C# 4.0 yet, named parameters don't work:
scheduler.Shutdown(true);
This is not a complete example but might get you on the right path. I would implement something like this:
class customSchedulerClass : IDisposable
{
private Component component = new Component();
private bool disposed = false;
public void scheduleSomeStuff()
{
//This is where you would implement the Quartz.net stuff
}
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!this=disposed)
{
if(disposing)
{
component.dispose;
}
}
disposed = true;
}
}
Then with this you can do cool stuff like using statements:
public static void Main()
{
using (customSchedulerClass myScheduler = new customSchedulerClass())
{
c.scheduleSomeStuff();
}
console.WriteLine("Now that you're out of the using statement the resources have been disposed");
}
So basically by implementing you code while inheriting the functionality of IDisposable you can then us the using statement and when you're done it will cleanly dispose your resources and keep things nice and clean. (Disclaimer, again this is not a complete example, just to get you in the right direction).
The docs don't say anything about IScheduler implementing IDisposable. If you have custom job types that grab and hold resources (file locks, database connections), you can implement IDispoable and override Dispose() on your object to release resources.
Generally we don't need to set an object to null in order to dispose it off.
If an object contains unmanaged resources then it should implement IDisposable (and be called by all its clients).
You can refere this similar post.
Edit - New Question
Ok lets rephrase the question more generically.
Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.
I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.
Background
We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be
disposed of, those implement the IDisposable interface.
The Problem
Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable,
to "automatically" call base.Dispose(bDisposing) if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing
or stops implementing IDisposable that will be taken care of automatically.
The issue is two folds.
First, finding if any ancestors implements IDisposable.
Second, calling base.Dispose(bDisposing) conditionally.
The first part, finding about ancestors implementing IDisposable, I have been able to deal with.
The second part is the tricky one. Despite all my
efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused
compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.
The main issue is that you cannot actually refer to base.Dispose() directly in your code if there is no such thing as an
ancestor implementing it (be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such
a thing happens in the future). That leave us with the Reflection mechanisms, but I did not find a proper way of doing it. Our code is quite filled with
advanced reflection techniques and I think I did not miss anything obvious there.
My Solution
My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build
(if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).
Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose()
methods throughout the hierarchy. Any new classes are created from templates that also includes this code.
public class MyOtherClassBase
{
// ...
}
public class MyDerivedClass : MyOtherClassBase, ICalibrable
{
private bool m_bDisposed = false;
~MyDerivedClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed) {
if (bDisposing) {
// Dispose managed resources
}
// Dispose unmanaged resources
}
m_bDisposed = true;
Type baseType = typeof(MyDerivedClass).BaseType;
if (baseType != null) {
if (baseType.GetInterface("IDisposable") != null) {
// If you have no ancestors implementing base.Dispose(...), comment
// the following line AND uncomment the throw.
//
// This way, if any of your ancestors decide one day to implement
// IDisposable you will know about it right away and proceed to
// uncomment the base.Dispose(...) in addition to commenting the throw.
//base.Dispose(bDisposing);
throw new ApplicationException("Ancestor base.Dispose(...) not called - "
+ baseType.ToString());
}
}
}
}
So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?
More Background
There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable.
If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with
calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.
The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short.
Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run on a separate, dedicated thread which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often.
Generally, you should implement a small resource wrapper class that only manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue.
If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter.
WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named components, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose components is generated, but dropping a component onto the surface does not generate the code to add it to components. You have to do this yourself in your constructor after calling InitializeComponent.
Personally, I think you might be better off handling this with something like FxCop. You should be able to write a rule that check so see if when an object is created that implements IDisposable that you use a using statement.
It seems a little dirty (to me) to automatically dispose an object.
There is not an "accepted" way of doing this. You really want to make your clean up logic (whether it runs inside of a Dispose or a finalizer) as simple as possible so it won't fail. Using reflection inside of a dispose (and especially a finalizer) is generally a bad idea.
As far as implementing finalizers, in general you don't need to. Finalizers add a cost to your object and are hard to write correctly as most of the assumptions you can normally make about the state of the object and the runtime are not valid.
See this article for more information on the Dispose pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestDisposeInheritance
{
class Program
{
static void Main(string[] args)
{
classC c = new classC();
c.Dispose();
}
}
class classA: IDisposable
{
private bool m_bDisposed;
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose A");
}
// Dispose unmanaged resources
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
Console.WriteLine("Disposing A");
}
}
class classB : classA, IDisposable
{
private bool m_bDisposed;
public void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
Console.WriteLine("Disposing B");
}
protected override void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose B");
}
// Dispose unmanaged resources
}
}
}
class classC : classB, IDisposable
{
private bool m_bDisposed;
public void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
Console.WriteLine("Disposing C");
}
protected override void Dispose(bool bDisposing)
{
if (!m_bDisposed)
{
if (bDisposing)
{
// Dispose managed resources
Console.WriteLine("Dispose C");
}
// Dispose unmanaged resources
}
}
}
}
If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.
If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.
Try this. It's a one-line addition to the Dispose() method, and calls the ancestor's dispose, if it exists. (Note that Dispose(bool) is not a member of IDisposable)
// Disposal Helper Functions
public static class Disposing
{
// Executes IDisposable.Dispose() if it exists.
public static void DisposeSuperclass(object o)
{
Type baseType = o.GetType().BaseType;
bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);
if (superclassIsDisposable)
{
System.Reflection.MethodInfo baseDispose = baseType.GetMethod("Dispose", new Type[] { });
baseDispose.Invoke(o, null);
}
}
}
class classA: IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposing A");
}
}
class classB : classA, IDisposable
{
}
class classC : classB, IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposing C");
Disposing.DisposeSuperclass(this);
}
}
public class MyVeryBaseClass {
protected void RealDispose(bool isDisposing) {
IDisposable tryme = this as IDisposable;
if (tryme != null) { // we implement IDisposable
this.Dispose();
base.RealDispose(isDisposing);
}
}
}
public class FirstChild : MyVeryBaseClasee {
//non-disposable
}
public class SecondChild : FirstChild, IDisposable {
~SecondChild() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
base.RealDispose(true);
}
protected virtual void Dispose(bool bDisposing) {
if (!m_bDisposed) {
if (bDisposing) {
}// Dispose managed resources
} // Dispose unmanaged resources
}
}
That way, you are responsible to implement right only the first class which is IDisposable.