Calling a method of a base class' base class

Friday, July 09, 2010 by Just* Team | Comments 2

Yesterday a colleague of mine asked me a question about how to invoke a method of a base class' base class. Although it is possible it is not a good idea (read more on stackoverflow). The basic idea is to avoid MethodDesc::IsVtableMethod() check (see Shared Source Common Language Infrastructure). That said here is the code.

 

using System;
 
namespace BaseBaseDemo
{
    class A
    {
        public virtual void M(string text)
        {
            Console.WriteLine("A:M({0})", text);
        }
    }
 
    class B : A
    {
        public override void M(string text)
        {
            Console.WriteLine("B:M({0})", text);
        }
    }
 
    class C : B
    {
        delegate void DelM(string text);
 
        public override void M(string text)
        {
            var ptr = this.GetType()
                        .BaseType.BaseType
                        .GetMethod("M").MethodHandle.GetFunctionPointer();
 
            var m = typeof(DelM)
                    .GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })
                    .Invoke(new object[] { this, ptr }) as DelM;
 
            m(text); // base.base.M(text);
            base.M(text);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            new C().M("test");
        }
    }
}

 

Posted in: .NET

2 Comments

  • Surya 12 Jul 2010
    What is the real-world example for needing this?
  • Mihail 12 Jul 2010
    Hi Surya,
    As stated calling base.base.Method() is not good idea. One should not need this kind of functionality. Please read Eric Lippert's comments on stackoverflow thread. The question of my colleague was provoked by curiosity, not by real-world scenario.

Add comment

  1. Formatting options
       
     
     
     
     
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)