Search code examples
c#c++oopinheritancevirtual

C# virtual methods


In C++ I was able to do this

class App
{
public:
    virtual void OnMouseMove(etc);
    void FunctionThatDoesStuff();
};

void App::FunctionThatDoesStuff()
{
    // Engine stuff here
    OnMouseMove(etc);
}

class ProjectName : public App
{
public:
    void OnMouseMove(etc);
};

void ProjectName::OnMouseMove(etc)
{
    // User stuff here
}

Then when OnMouseMove was called from FunctionThatDoesStuff in App it would be overrode and it would call ProjectName.OnMouseMove instead. But in C# I couldn't do this. This was my first attempt.

public class App
{
    protected void MouseMove()
    {
        // Engine code here
        OnMouseMove(etc);
    }

    protected virtual void OnMouseMove(etc)
    {
        // Do Nothing
    }
}

public class ProjectName : App
{
    protected override void OnMouseMove(etc)
    {
        // User code here
    }
}

I tried using delegates since they were just functions that aren't implemented. This did not work though. How could I achieve the equivalent in C#? I imagine I could work around it and use events. But is there a more similar way to do this.


Solution

  • If I understand you are talking about abstract methods or classes:

    public abstract class App
    {
        protected void MouseMove()
        {
            // Engine code here
        }
    
        protected abstract void OnMouseMove(object etc);
    }
    
    public class ProjectName : App
    {
        protected override void OnMouseMove(object etc)
        {
            // User code here
        }
    }