Search code examples
c#virtual

function overrides not calling


I'm having a problem with a program I'm writing, where my virtual functions don't seem to be behaving the way they should.

I have a class with a virtual function, and a derived class that overrides it. When I call the function, the override isn't called, but the base is. This is something I've done a million times before and I have no idea how that behaviour can break in such as simple case.

As an example:

public class ClassA
{
  public DoStuff()
  {
    MyVirtual()
  }

  protected virtual MyVirtual()
  {
    Console.WriteLine("Base MyVirtual Called");
  }
}

public class ClassB : ClassA
{
  protected override MyVirtual()
  {
    Console.WriteLine("Overridden MyVirtual Called");
  }
}

ClassA test = new ClassB;
test.DoStuff();

This example is just for effect (I haven't compiled it to check it, I'm just demonstrating). I just want to know what can break that so the override isn't called. I can't paste my specific code, but it is theoretically as simple as that.

  • The inheritance hierarchy is just the two classes
  • There's no sealed modifiers
  • The class is created via a simple call to new for the inherited class
  • The virtual function is protected and called from a public function in the base class just like that

How could that possibly break or what could interfere with that behaviour? The project is quite complicated, but this is nothing new that I'm implementing. In my specific code, there is even another virtual function written exactly the same way and inherited the same way, that works fine. I even made the new function by copy/pasting that one and renaming, so the syntax should be identical (I did rebuild them from scratch when they didn't work, but no difference to their behaviour).

Anyway, I'm at my wits end and I can't spend days searching for an obscure reason for this, so any ideas of where to start looking would be hugely appreciated.


Solution

  • If you fix the errors it compiles successfully and behaves as you would expect.

    Fixed version:

    public class ClassA
    {
      public void DoStuff()
      {
        MyVirtual();
      }
    
      protected virtual void MyVirtual()
      {
        Console.WriteLine("Base MyVirtual Called");
      }
    }
    
    public class ClassB : ClassA
    {
      protected override void MyVirtual()
      {
        Console.WriteLine("Overridden MyVirtual Called");
      }
    }
    
    ClassA test = new ClassB();
    test.DoStuff();
    

    Output:

    Overridden MyVirtual Called
    

    This basically means that, contrary to your statements, your code isn't "theoretically as simple as that", my guess is that you are not actually overriding in B class.