Barry MSIH
Barry MSIH

Reputation: 3787

Why Return Base Method With Blazor OnInitialized Method

I am seeing more and more examples of OnInitialized and OnInitializedAsync() returning base.OnInitialized[Async]. But Why? The examples on the Microsoft website do not include returning the base method

protected override Task OnInitializedAsync()
{
    Contact = new();
    return base.OnInitializedAsync();
}

Upvotes: 22

Views: 8927

Answers (3)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30320

As this question is referred from elsewhere, for reference here's what the ComponentBase methods look like:

    protected virtual void OnInitialized()
    {
    }

    protected virtual Task OnInitializedAsync()
        => Task.CompletedTask;

    protected virtual void OnParametersSet()
    {
    }

    protected virtual Task OnParametersSetAsync()
        => Task.CompletedTask;

    protected virtual void OnAfterRender(bool firstRender)
    {
    }

    protected virtual Task OnAfterRenderAsync(bool firstRender)
        => Task.CompletedTask;

Upvotes: 6

Rodion Mostovoi
Rodion Mostovoi

Reputation: 1593

As @neil-w mentioned, your razor component may inherit another custom component, so in this case if a custom component does something in OnInitialized or in OnInitializedAsync you will broke the logic if you don't call these methods. So, it costs to add base methods calling to avoid possible errors. Also, the right way is to call a creation methods logic in the beginning, and a destruction logic in the end of your function.
So, the correct code from your example will be:

protected override async Task OnInitializedAsync()
{
    await base.OnInitializedAsync();
    Contact = new();
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273621

It isn't required and you shouldn't add them, just to avoid clutter.

Those life-cycle methods are all virtual empty methods. They are for all intents and purposes abstract but declaring them as such would have required you to override all of them.

Except of course when documented otherwise, as with SetParametersAsync. But there the choice of whether and where you call the base implementation is very much part of your logic, see the "If base.SetParametersAsync isn't invoked" part.

Upvotes: 26

Related Questions