How to call an explicitly implemented interface-method on the base class

c# call interface method
c# interface implementation
c# implement interface with different name
c# interface new method
how to restrict interface method in c#
c# interface vs class
can you instantiate an interface
c# force interface implementation

I have a situation, where two classes (one deriving from the other) both implement the same interface explicitly:

interface I
{
  int M();
}

class A : I
{
  int I.M() { return 1; }
}

class B : A, I
{
  int I.M() { return 2; }
}

From the derived class' implementation of I.M(), I'd like to call the implementation of the base class, but I don't see how to do it. What I tried so far is this (in class B):

int I.M() { return (base as I).M() + 2; }
// this gives a compile-time error
//error CS0175: Use of keyword 'base' is not valid in this context

int I.M() { return ((this as A) as I).M() + 2; }
// this results in an endless loop, since it calls B's implementation

Is there a way to do this, without having to implement another (non interface-explicit) helper method?


Update:

I know it's possible with a "helper" method which can be called by the derived class, e.g:

class A : I
{
    int I.M() { return M2(); }
    protected int M2 { return 1; }
}

I can also change it to implement the interface non-explicitly. But I was just wondering if it's possible without any of these workarounds.

Unfortunately, it isn't possible. Not even with a helper method. The helper method has the same problems as your second attempt: this is of type B, even in the base class and will call the implementation of M in B:

interface I
{
  int M();
}
class A : I
{
  int I.M() { return 1; }
  protected int CallM() { return (this as I).M(); }
}
class B : A, I
{
  int I.M() { return CallM(); }
}

The only workaround would be a helper method in A that is used in A's implementation of M:

interface I
{
  int M();
}
class A : I
{
  int I.M() { return CallM(); }
  protected int CallM() { return 1; }
}
class B : A, I
{
  int I.M() { return CallM(); }
}

But you would need to provide a method like this also for B if there will be a class C : B, I...

Explicit Interface Implementation, A class can implement interfaces that contain a member with the In the following example, all the calls to Paint invoke the same method. Explicit Interface Implementation (C# Programming Guide) 01/24/2020; 2 minutes to read +4; In this article. If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

It is possible using reflection. The code follows. I added caching as a basic optimization, but it can be optimized further by using Delegate.CreateDelegate on methodInfo. Also, parameter count and type checks can be added using methodInfo.GetParameters().

interface I   
{   
    int M();   
} 

class A : I   
{   
    int I.M() { return 1; }   
} 

class B : A, I   
{   
    BaseClassExplicitInterfaceInvoker<B> invoker = new BaseClassExplicitInterfaceInvoker<B>();
    int I.M() { return invoker.Invoke<int>(this, "M") + 2; }   
}

public class BaseClassExplicitInterfaceInvoker<T>
{
    private Dictionary<string, MethodInfo> cache = new Dictionary<string, MethodInfo>();
    private Type baseType = typeof(T).BaseType;

    private MethodInfo FindMethod(string methodName)
    {
        MethodInfo method = null;
        if (!cache.TryGetValue(methodName, out method))
        {
            var methods = baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var methodInfo in methods)
            {
                if (methodInfo.IsFinal && methodInfo.IsPrivate) //explicit interface implementation
                {
                    if (methodInfo.Name == methodName || methodInfo.Name.EndsWith("." + methodName))
                    {
                        method = methodInfo;
                        break;
                    }
                }
            }   

            cache.Add(methodName, method);
        }

        return method;
    }

    public RT Invoke<RT>(T obj, string methodName)
    {            
        MethodInfo method = FindMethod(methodName);
        return (RT)method.Invoke(obj, null);
    }

}   //public static class BaseClassExplicitInterfaceInvoker<T>

Here is the source of my inspiration.

Calling base-class implementation of interface methods, How can I call the base class implementation of this interface had to do was remove the explicit declaration of the method in both classes:. We all know the problem of not being able to define a winforms class as abstract if you want to be able to use the designer (see this question). I created an Interface that contains the method signatures that need to be implemented in a derived form. I then call the Interface methods directly from the base class like such:

it is necessary explicitly?... Can you use an abstract class or class instead of interface?

interface ISample {}
class A : ISample {}
class B : A {}
...
base.fun();
...

http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx

I have no idea its not possible call base method when it comes from implementation of interface.

C#, C# doesn't support the concept of Multiple Inheritance because of the If a class implements from more than one interface that has methods with the then the call to such a method will implement the same method and not� After playing around with the code, I actually realized that the problem was that I implemented the interface explicitly in the helper class. This prefixed the method name with the interface name. By doing this, I syntactically prevented calling of the method from the derived class.

You can't call Explicit interface method in base class,here i solved this issue

I have two interface -> Interface1 and Interface2

public interface Interface1
{      
    string method2();      
}

public interface Interface2
{   
    string method22();

}

Main class Method

class Program
{
    static void Main(string[] args)
    {

        class1 cls = new class1();
        string str = cls.method2();
    }
}

and my interface implemented class

class class1 : Interface1, Interface2
{

    #region Interface1 Members

    public string method2()
    {
        return (this as Interface2).method22();
    }      

    #endregion

    #region Interface2 Members      

    string Interface2.method22()
    {
        return "2";
    }

    #endregion
}

What are good reasons to use explicit interface implementation for , Imagine a situation where an interface forces a class to implement methods which do However in C#, I had to use explicit interfaces to achieve the same thing. In the following example, all the calls to Paint invoke the same method. DoExternalStuff(); } interface IInternal { void DoInternalStuff(); } class Parent : IExternal� I want to explicitly implement an interface method on a base class. Beyond this, I wanted to make this method virtual so I could override it on a derived class, but explicitly implemented methods do not allow this. I have tried making a protected virtual method in the base, calling this from the int

using System;

namespace SampleTest
{
    interface IInterface1
    {
        void Run();
    }

    interface IInterface2
    {
        void Run();
    }

    public class BaseClass : IInterface1, IInterface2
    {
        public void Interface1Run()
        {
            (this as IInterface1).Run();
        }

        public void Interface2Run()
        {
            (this as IInterface2).Run();
        }

        void IInterface2.Run()
        {
            Console.WriteLine("I am from interface 2");
        }

        void IInterface1.Run()
        {
            Console.WriteLine("I am from interface 1");
        }
    }

    public class ChildClass : BaseClass
    {
        public void ChildClassMethod()
        {
            Interface1Run();
            Interface2Run();      
        }
    }
    public class Program : ChildClass
    {
        static void Main(string[] args)
        {
            ChildClass childclass = new ChildClass();
            childclass.ChildClassMethod();
        }
    }
}

Implementing an Interface in Python – Real Python, Using Metaclasses; Using Virtual Base Classes An informal Python interface is a class that defines methods that can be By using a metaclass, you don't need to explicitly define the subclasses. Your code will call . Beyond this, I wanted to make this method virtual so I could override it on a derived class, but explicitly implemented methods do not allow this. I have tried making a protected virtual method in the base, calling this from the interface method, and then overriding this method in the derived class.

C# pitfall: Interface methods should be callable by derived types, When a base type explicitly implements a public interface method, that method is only If the derived type explicitly overrides that interface method, the base implementation becomes inaccessible. MyMethod() would be a recursive call } }� How to explicitly implement members of two interfaces (C# Programming Guide) 07/20/2015; 2 minutes to read +5; In this article. Explicit interface implementation also allows the programmer to implement two interfaces that have the same member names and give each interface member a separate implementation.

Java Interfaces, Java interfaces specify what methods a class implementing that Default Methods; Interface Static Methods; Interfaces and Inheritance a default method simply by implementing that method explicitly, as is done Here is an example of calling the static print() method from the above MyInterface interface: Ok I derive a type B from a base class A. A implements IDisposable explicit but I have to do additional cleanup in B, so I implement IDisposable in B: interface IDisposable with member i.Dispose() = // additional work base.Dispose() // IDisposable).Dispose() yields compiler error: Unexpected sy

Traits, 1, implementing class will have to declare the name method You might consider creating a base class which implements the desired trait(s) if you want Traits can call any dynamic code, like a normal Groovy class. exist in an implementing class, without having to explicitly declare them in an interface. How to Call an Interface Method in Java. In order to call an interface method from a Java program, the program must first instantiate the interface implementation program. A method can then be called using the implementation object. To learn how to call an interface method in Java, follow these 10 steps.

Comments
  • Yes that workaround is what I have added to the updated question. But it's not what I wanted to know.
  • @M4N: That is just to make the answer a bit bigger ;-) The real answer is the first sentence: It is impossible without such workarounds.
  • To add to why it's impossible: Explicitly implemented interface methods are made private - making them impossible to call from a derived class. You should probably prefer a different method like the one Daniel listed anyway, to avoid the call super code smell.
  • Thanks for explaining why it is impossible, I understand now.
  • @DanielHilgarth Thanks for the post, this saved me some time.
  • Works like a charm. Reflection is the way to go in this case.
  • Just because you can do something it does not mean that you have to do it.
  • Just because you should probably consider not doing something does not mean there aren't instances where doing it is indispensable ;-) @Roland, thanks for sharing, works a treat!
  • No! B has a different implementation of the interface than A (it adds something to A's implementation).
  • @M4N - Then you can only extend A override the method and make a base call to the method and continue implementing the method.
  • See updated question. (explicit implementation is not necessary, but I was just wondering whether it's possible)
  • Add some explnation