liveBook · Manning

Generics

As explained in Pro ASP.NET Core 7, Tenth Edition

A generic type parameter is a placeholder type specified in a generic type or method declaration and replaced by a concrete type when the generic construct is used.

Generics make a Blazor template component data-aware. A type parameter identifies the row type, allowing one component to render different data models and add shared behavior. section 34.3.2

Implement a generic template component by:

  • Declaring the parameter with @typeparam RowType. section 34.3.2
  • Accepting data through IEnumerable<RowType> RowData. section 34.3.2
  • Accepting row markup through RenderFragment<RowType> RowTemplate. section 34.3.2
  • Iterating over RowData and invoking RowTemplate(item) for each row. section 34.3.2

Reuse the table for people

Use <TableTemplate RowType="Person" RowData="People"> with a header and a RowTemplate that displays each person's identifier, name, department, and location. The same component can then render departments by changing RowType, data, and row markup. section 34.3.2

Listing 34.19 Adding a type parameter in the Blazor/TableTemplate.razor file
@typeparam RowType
<table class="table table-sm table-bordered table-striped">
    @if (Header != null) {
        <thead>@Header</thead>
    }
    <tbody>
        @if (RowData != null && RowTemplate != null) {
            @foreach (RowType item in RowData) {
                <tr>@RowTemplate(item)</tr>
            }
        }
    </tbody>
</table>

@code {

    [Parameter]
    public RenderFragment? Header { get; set; }
        
    [Parameter]
    public RenderFragment<RowType>? RowTemplate { get; set; }
        
    [Parameter]
    public IEnumerable<RowType>? RowData { get; set; }
}

Inspect the complete TableTemplate.razor implementation, including its type parameter, typed data collection, and typed row template. section 34.3.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains declaration, typed parameters, row iteration, reuse, and optional C# where constraints.
Examples
Demonstrates reusable tables for Person and Department entities with typed row templates, sorting, highlighting, and related data.
What it assumes
Assumes Blazor components, Razor syntax, component parameters, and C# types while introducing generic component declarations.
What you can do after
Build reusable Blazor template components that accept typed sequences and render caller-provided content for each item.
How it connects
Connects generics with Blazor components, RenderFragment, component parameters, data templates, and C# type constraints.

Also explained in

Compare how 20 books explain generics →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.