Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of "base.OnNavigatedTo(e)" inside of the OnNavigatedTo override method?

When overriding the OnNavigatedTo method in a page they place this line of code inside:

base.OnNavigatedTo(e);

I've been removing it and have not noticed any odd behavior. What is this line of code for? Are we supposed to leave it? Or is this like a place holder?

I'm pretty sure this isn't specific to the method itself, as I have seen this in different places. My guess is that this calls the default OnNavigatedTo method from the from the class that we are inheriting from (in this case Page). Its existence doesn't really make sense though, because if we wanted that why override it in the first place? Can someone explain how this works?

like image 574
Edward Avatar asked Mar 08 '12 19:03

Edward


3 Answers

(Not specific to OnNavigatedTo): This is limitation of virtual OnXXX methods (or any virtual method) - derived class formally doesn't know if base class have any non-trivial functionality. As result you have to dig into documentation (if one exists) or rely on testing to know if you should call base class or not. If you need to use someones library - calling base method is safer default.

There are different approaches to solve "do I need to call base implementation of virtual method" depending on context when you designing your own library.

like image 81
Alexei Levenkov Avatar answered Nov 09 '22 13:11

Alexei Levenkov


It isn't as picky as Android is (which crashes with SuperNotCalledException). But here's a use case for leaving it:

  public class BasePage : PhoneApplicationPage
    {
       protected override OnNavigatedTo(....)
    {
        //some logic that should happen on all your pages (logging to console, etc.)
    }
    }

    public class DetailsPage : BasePage
    {
      protected override OnNavigatedTo(....)
    {
    base.OnNavigatedTo(); //the basepage logging, etc.
        //custom page logic (setup VM, querystring parameters, etc.)
    }

}

In general, i'd call it. If the implementation of PhoneApplicationPage changes, and that Virtual function has more in it, you don't want to miss out ;)

like image 45
William Melani Avatar answered Nov 09 '22 14:11

William Melani


You can check these things in reflector. The framework does it's job in the InternalOnNavigatedTo method, which calls the empty OnNavigatedTo virtual method:

protected virtual void OnNavigatedTo(NavigationEventArgs e) { }

You can delete that line, it has no function, but this is not a general rule. If you don't know what are the base functions do, leave the calls there.

like image 5
Loránd Biró Avatar answered Nov 09 '22 15:11

Loránd Biró