How do I call an explicit method of an interface in a base class in C #?

C # has a useful explicit interface feature that allows you to create methods that implement interfaces while avoiding name collisions.

public abstract class BaseClass : IDisposable {
  public int Value;
  void IDisposable.Dispose() => Value = 1;
}

      

You can even override these methods in subclasses, as long as the subclass also explicitly indicates that it implements the interface.

public class SubClass : BaseClass, IDisposable {
  void IDisposable.Dispose() => Value = 2;
}

static void Main() {
  BaseClass obj = new SubClass();
  ((IDisposable)obj).Dispose();
  Console.WriteLine(obj.Value); // 2
}

      

Within a subclass, you can usually call base.Whatever

to access versions of the base class methods. But with explicit implementations of the interface, this syntax is not valid. Also, there is no way to cast the base to the interface in order to call the method.

How do I access logic in explicit implementations of the base class interface?

+3


source to share


1 answer


I hope this is helpful:



 public abstract class BaseClass : IDisposable
 {
        public int Value;
        void IDisposable.Dispose() => DoSomething();
        public void DoSomething() => Value = 1;
 }

 public class SubClass : BaseClass, IDisposable
 {
        void IDisposable.Dispose()
        {
            if (Condition())
                DoSomething();
            else
                DoSomethingElse();
        }

        void DoSomethingElse() => Value = 2;

        private bool Condition()
        {
            return true;
        }


 }

      

+1


source







All Articles