How Inheritance in Blazor Works?

How Inheritance in Blazor Works?

The ComponentBase Class

When a Blazor component is created, it should inherit from the ComponentBase class. The first reason for so doing is that it implements the IComponent interface which Blazor uses to locate components throughout the project. Secondly, ComponentBase contains important lifecycle methods.

Let’s continue with the GetStarted Blazor solution that we created here in our post on templated components. We have since, built further with this solution on the past few blogs on routing in Blazor and lifecycle methods

Derived Class from ComponentBase

Now in the same solution, we add a CoolBlazorBase class at the project root,(but you can add it anywhere like the Pages folder or a dedicated Components folder). The following is the code for this CoolBlazorBase class (from which we shall inherit in a child component)

CoolBlazorBase.cs

using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetStartedBlazor
{
    public class CoolBlazorBase : ComponentBase
    {
        public string CoolBlazorText { get; set; } = "Blazor is cool!";

        public int TestMethod (int a, int b)
        {
            return a + b;
        }
    }
}

We can see here that the CoolBlazerBase class derives from the ComponentBase class. In this simple class we just create a property that returns a string and has a method that returns the sum of two integers that it accepts as parameters. Now within the Pages folder create a razor component called CoolBlazor.razor and paste the following code to replace the default code

Creating the Child Component

CoolBlazor.razor

@page "/CoolBlazor"
@inherits GetStartedBlazor.CoolBlazorBase
<h1>@CoolBlazorText</h1>
<h2>The result of calling the test method is : @TestMethod(23, 34)</h2>



This component inherits from the CoolBlazorBase class with the @inherits directive and hence can use the public property CoolBlazorText and the TestMethod of the base class. The @page directive at the top enables us to browse to the CoolBlazor component by a request like this: https://localhost:port/CoolBlazor.

Testing the Child Component

The result of running this application is as per the following screen


We can see that the CoolBlazorText value “Blazor is Cool!” is passed to the child component and observe that the output 57 is the result of passing 23 and 34 to the TestMethod in the CoolBlazor child component which demonstrates inheritance in Blazor.

YouTube Version

The YouTube version of this post is here

Follow Me Here

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.