Lacrymology
Lacrymology

Reputation: 2259

Method overriding in C#

This is a rather simple question, I have a base class which implements common GUI elements, and a series of child classes which I want to override a given method, so they can implement their own behavior on a common control (namely, Prev and Next buttons).

So I have this

public class MetalGUI : BaseGUI {
    new protected void OnGUI()
    {
        base.OnGUI();
        if(GUI.Button(prevRect, "BACK", "ButtonLeft"))
            OnPrev();

        if(GUI.Button(nextRect, "NEXT", "ButtonRight"))
            OnNext();

    }

    virtual protected void OnPrev(){}
    virtual protected void OnNext(){}
}

and this is one of the child classes

public class MissionSelectGUI : MetalGUI {
    new void OnGUI()
    {
        base.OnGUI();
    }

    new protected void OnPrev()
    {
        Application.LoadLevel("mainMenu");
    }
    new protected void OnNext()
    {
        Application.LoadLevel("selectPlayer");
    }
}

(both classes have been stripped off the stuff non-essential for this case)

The thing is that when I have a member of MissionSelectGUI instantiated, the OnPrev and OnNext on MetalGUI is getting called instead of the overriden methods. Why is this?

Upvotes: 1

Views: 2974

Answers (4)

Ricibob
Ricibob

Reputation: 7705

Your using the new keyword in your derived class on your OnPrev/OnNext methods - what you want to do is "override" the base class methods eg use the override keyword.

Upvotes: 2

Oded
Oded

Reputation: 498904

You have not overridden the methods, just hidden them using new.

This is how you would override them (and allow further classes to override this implementation):

override protected void OnPrev()
{
    Application.LoadLevel("mainMenu");
}

Upvotes: 1

Etienne de Martel
Etienne de Martel

Reputation: 36852

Because new shadows (or hides) the method (it creates a new method with the same name). To override it (thus adding an entry in the class' vtable), use override. For instance:

override protected void OnPrev()
{
    Application.LoadLevel("mainMenu");
}

Upvotes: 9

Mike Miller
Mike Miller

Reputation: 16575

I think you should be using the overrides keyword not the new one. see http://msdn.microsoft.com/en-us/library/51y09td4(v=vs.71).aspx#vclrfnew_newmodifier.

Upvotes: 2

Related Questions