JP Garza
JP Garza

Reputation: 270

What does base.OnStartup(e) do?

I see that many people use "base.OnStartup(e)" inside of App.xaml.cs like this:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    MainWindow app = new MainWindow();
    app.Show();
}

Is there a need for it? What is the purpose for it?

Upvotes: 3

Views: 2471

Answers (2)

ASh
ASh

Reputation: 35703

.NET Framework code can be found on https://referencesource.microsoft.com

Application.OnStartup() doesn't contain much functionality:

/// <summary>
///     OnStartup is called to raise the Startup event. The developer will typically override this method
///     if they want to take action at startup time ( or they may choose to attach an event).
///     This method will be called once when the application begins, once that application's Run() method
///     has been called.
/// </summary>
/// <param name="e">The event args that will be passed to the Startup event</param>
protected virtual void OnStartup(StartupEventArgs e)
{
    // Verifies that the calling thread has access to this object.
    VerifyAccess();

    StartupEventHandler handler = (StartupEventHandler)Events[EVENT_STARTUP];
    if (handler != null)
    {
        handler(this, e);
    }
}

instead of overriding OnStartup() we can add a handler to Startup event:

<Application x:Class="WpfApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="LaunchWpfApp"> 

private void LaunchWpfApp(object sender, StartupEventArgs e)
{
    MaiWindow app = new MainWindow();
    app.Show();
}

Upvotes: 3

BradleyDotNET
BradleyDotNET

Reputation: 61359

It allows any base class logic to run; just like any other usage of base.

Its probably not strictly necessary; but calling a base class's implementation when overriding virtual methods is considered a best practice (unless you actively want to suppress the base behavior).

Upvotes: 4

Related Questions