<h2>Edit - New Question</h2>

<p>Ok lets rephrase the question more generically. </p>

<p>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.</p>

<p>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.</p>

<h2>Background</h2>

<p>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 <strong>IDisposable</strong> interface.</p>

<h2>The Problem</h2>

<p>Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable, 
to "automatically" call <strong>base.Dispose(bDisposing)</strong> 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.</p>

<p>The issue is two folds. </p>

<ul>
<li>First, finding if any ancestors implements IDisposable. </li>
<li>Second, calling base.Dispose(bDisposing) conditionally.</li>
</ul>

<p>The first part, finding about ancestors implementing IDisposable, I have been able to deal with. </p>

<p>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.</p>

<p>The main issue is that you <strong>cannot actually refer to base.Dispose()</strong> directly in your code if there is no such thing as an 
ancestor implementing it (<em>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</em>). That leave us with the <strong>Reflection</strong> 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.</p>

<h2>My Solution</h2>

<p>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).</p>

<p>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. </p>

<pre><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());
            }
        }
    }
}
</code></pre>

<p><strong>So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?</strong></p>

<h2>More Background</h2>

<p>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.</p>

[{'answer_id': 78226, 'author': 'Bryant', 'author_id': 10893, 'author_profile': 'https://Stackoverflow.com/users/10893', 'pm_score': 2, 'selected': False, 'text': '<p>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. </p>\n\n<p>It seems a little dirty (to me) to automatically dispose an object.</p>\n'}, {'answer_id': 78259, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 78287, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': 0, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 78315, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<p>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 <em>on a separate, dedicated thread</em> 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.</p>\n\n<p>Generally, you should implement a small resource wrapper class that <em>only</em> 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.</p>\n\n<p>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.</p>\n\n<p>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 <code>components</code>, 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 <code>components</code> is generated, <em>but dropping a component onto the surface does not generate the code to add it to <code>components</code></em>. You have to do this yourself in your constructor after calling InitializeComponent.</p>\n"}, {'answer_id': 78322, 'author': 'Sunny Milenov', 'author_id': 8220, 'author_profile': 'https://Stackoverflow.com/users/8220', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public class MyVeryBaseClass {\n    protected void RealDispose(bool isDisposing) {\n        IDisposable tryme = this as IDisposable;\n        if (tryme != null) { // we implement IDisposable\n            this.Dispose();\n            base.RealDispose(isDisposing);\n        }\n    }\n}\npublic class FirstChild : MyVeryBaseClasee {\n    //non-disposable\n}\npublic class SecondChild : FirstChild, IDisposable {\n    ~SecondChild() {\n        Dispose(false);\n    }\n    public void Dispose() {\n        Dispose(true);\n        GC.SuppressFinalize(this);\n        base.RealDispose(true);\n    }\n    protected virtual void Dispose(bool bDisposing) {\n        if (!m_bDisposed) {\n            if (bDisposing) {\n            }// Dispose managed resources\n        } // Dispose unmanaged resources\n    }\n}\n</code></pre>\n\n<p>That way, you are responsible to implement right only the first class which is IDisposable.</p>\n'}, {'answer_id': 78458, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 0, 'selected': False, 'text': '<p>Try this. It\'s a one-line addition to the Dispose() method, and calls the ancestor\'s dispose, if it exists. (Note that <code>Dispose(bool)</code> is not a member of <code>IDisposable</code>)</p>\n\n<pre><code>// Disposal Helper Functions\npublic static class Disposing\n{\n    // Executes IDisposable.Dispose() if it exists.\n    public static void DisposeSuperclass(object o)\n    {\n        Type baseType = o.GetType().BaseType;\n        bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);\n        if (superclassIsDisposable)\n        {\n            System.Reflection.MethodInfo baseDispose = baseType.GetMethod("Dispose", new Type[] { });\n            baseDispose.Invoke(o, null);\n        }\n    }\n}\n\nclass classA: IDisposable\n{\n    public void Dispose()\n    {\n        Console.WriteLine("Disposing A");\n    }\n}\n\nclass classB : classA, IDisposable\n{\n}\n\nclass classC : classB, IDisposable\n{\n    public void Dispose()\n    {\n        Console.WriteLine("Disposing C");\n        Disposing.DisposeSuperclass(this);\n    }\n}\n</code></pre>\n'}, {'answer_id': 211599, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>See this <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">article</a> for more information on the Dispose pattern.</p>\n'}, {'answer_id': 3681224, 'author': 'SUmeet Khandelwal', 'author_id': 443903, 'author_profile': 'https://Stackoverflow.com/users/443903', 'pm_score': 2, 'selected': False, 'text': '<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestDisposeInheritance\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            classC c = new classC();\n            c.Dispose();\n        }\n    }\n\n    class classA: IDisposable \n    { \n        private bool m_bDisposed;\n        protected virtual void Dispose(bool bDisposing)\n        {\n            if (!m_bDisposed)\n            {\n                if (bDisposing)\n                {\n                    // Dispose managed resources\n                    Console.WriteLine("Dispose A"); \n                }\n                // Dispose unmanaged resources \n            }\n        }\n        public void Dispose() \n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n            Console.WriteLine("Disposing A"); \n        } \n    } \n\n    class classB : classA, IDisposable \n    {\n        private bool m_bDisposed;\n        public void Dispose()\n        {\n            Dispose(true);\n            base.Dispose();\n            GC.SuppressFinalize(this);\n            Console.WriteLine("Disposing B");\n        }\n\n        protected override void Dispose(bool bDisposing)\n        {\n            if (!m_bDisposed)\n            {\n                if (bDisposing)\n                {\n                    // Dispose managed resources\n                    Console.WriteLine("Dispose B");\n                }\n                // Dispose unmanaged resources \n            }\n        }\n    } \n\n    class classC : classB, IDisposable \n    {\n        private bool m_bDisposed;\n        public void Dispose() \n        {\n            Dispose(true);\n            base.Dispose();\n            GC.SuppressFinalize(this);\n            Console.WriteLine("Disposing C");             \n        }\n        protected override void Dispose(bool bDisposing)\n        {\n            if (!m_bDisposed)\n            {\n                if (bDisposing)\n                {\n                    // Dispose managed resources\n                    Console.WriteLine("Dispose C");             \n                }\n                // Dispose unmanaged resources \n            }\n        }\n    } \n\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/78141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7984/']