Search code examples
c#typescastingupcasting

How can I override a virtual method, but still invoke the base class version in C#


I have a simple class hierarchy where I have a virtual method that is overriden. But at certain callsites I want to call the base class version of this method rather than the virtual method.

For example:

public class A {
    public virtual void Foo() {...}
}

public class B : A {
    public override void Foo() {...}
}

public class Program {
    public void SomeMethod()
    {
       ...

       //  ListofA is type IEnumerable<A>
       foreach (var item in ListofA)
       {
           // I want this to call A.Foo(), rather than B.Foo()
           // But everything I've tried, which has really just been casting, has resulted in B.Foo()
           item.Foo();
       }
    }
}

Solution

  • You can't on an override. Overrides replace the original (from the standpoint of the caller). An overridden method may call the base, but you can't externally.