Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a base function that's an explicit interface implementation?

Basic problem (pseudocode):

interface ISomethingDoer
{
   void DoSomething();
}

class A: ISomethingDoer
{
   void ISomethingDoer.DoSomething()
   {
      Something.Do();
   }
}

class B: A, ISomethingDoer
{
   void ISomethingDoer.DoSomething()
   {
      if (reason)
      {
         base.DoSomething(); //this does not compile
      }
      SomethingElse.Do();
   }
}

Is there any way to make this work without removing the explicit implementation from class A?

like image 454
Mason Wheeler Avatar asked Jan 23 '26 21:01

Mason Wheeler


1 Answers

I would suggest changing your base class a little such that DoSomething calls a protected method:

class A: ISomethingDoer
{
   void ISomethingDoer.DoSomething()
   {
       DoSomethingImpl();
   }

   protected void DoSomethingImpl()
   {
       Something.Do();
   }
}

And then in B you can call DoSomethingImpl:

class B: A, ISomethingDoer
{
   void ISomethingDoer.DoSomething()
   {
      if (reason)
      {
         DoSomethingImpl(); //this does compile
      }
      SomethingElse.Do();
   }
}

The alternative method suggested by Lasse V. Karlsen is to use reflection:

class B: A, ISomethingDoer
{
   void ISomethingDoer.DoSomething()
   {
      if (reason)
      {
         string baseName = $"{typeof(ISomethingDoer).FullName}.{nameof(DoSomething)}";
         MethodInfo baseMethod = this.GetType().BaseType
             .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
             .FirstOrDefault(m => m.IsPrivate && m.IsFinal && m.Name == baseName);
          baseMethod.Invoke(this, new object[0]);
      }
      SomethingElse.Do();
   }
}

But I don't like this approach since it uses reflection and is going to be slower. I used this answer to help me build the reflection solution.

You can use GetParameters() if you need to filter different overloads of the method, and you can specify arguments by building an object[] array containing them in the same positional order.

like image 138
DiplomacyNotWar Avatar answered Jan 25 '26 12:01

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!