Telerik blogs

Learn the benefits of using generic type arguments using the @typeparam directive to implement reusable and type-safe Razor components.

Generic type support brings generic types to Razor components, letting us build scalable Blazor web applications.

In this article, we will learn how to use generic types in our Razor components and when we might want to consider using them.

Hint: If you are new to generics in C#, please familiarize yourself first with generic types and methods in C# to be able to follow along.

You can access the code on GitHub.

Implementing a Simple Generic Razor Component

The @typeparam attribute allows us to define a generic parameter for a Razor component.

Consider the following simple generic NamedObjectRenderer component:

@typeparam TType where TType : INamedObject

<div>@Object.GetName()</div>

@code {
    [Parameter]
    public required TType Object { get; set; }
}

This component defines a generic type using the @typeparam directive.

We can then use TType as the type for the parameter property called Object.

Since we use a type constraint, we can use the GetName method defined in the INamedObject interface:

public interface INamedObject
{
    string GetName();
}

Now, let’s use the component.

@code {
    private Person person = new Person { Name = "Peter Parker", Age = 22 };

    public class Person : INamedObject
    {
        public required string Name { get; set; }
        public required int Age { get; set; }

        public string GetName()
        {
            return Name;
        }
    }
}

First, we create a Person class that implements the INamedObject interface. We add two properties Name and Age, and provide the value of the Name property in the GetName method from the INamedObject interface.

The usage of the NamedObjectRenderer component is straightforward:

<NamedObjectRenderer Object="person" />

We provide an object of the Person class as the argument for the Object parameter of the NamedObjectRenderer component.

Hint: Notice that we do not specifically provide the Person type as an argument for the TType parameter. That’s possible because Blazor is able to infer the type of the provided object.

It’s also possible to explicitly provide the type for the generic type argument. However, in most cases, type inference is good enough and makes using generic Razor components straightforward.

<NamedObjectRenderer Object="person" TType="Person" />

Implementing a Higher-Level Generic Razor Component

The previous example demonstrated the foundation of how to implement generic Razor components.

I agree that the example doesn’t feel revolutionary. There might be use cases here and there for it, but it does not change the general approach to how you will implement your Blazor web applications.

However, we can build on that foundation and implement a more advanced generic Razor component that has the potential to change how you structure and architect your Blazor web applications.

Consider the following scenario: We want to render two columns on the screen. A name and a value column. We want to implement a single component to encapsulate the behavior and the look and feel of the component.

But there is a twist! We want to be able to use that component with completely different data objects.

The following generic DataTable component is a great example:

@typeparam TItem

<table style="margin-top: 20px">
    <thead>
        <tr>
            <th style="width: 120px">Name</th>
            <th>Value</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Items)
        {
            <tr>
                <td>@GetName(item)</td>
                <td>@GetValue(item)</td>
            </tr>
        }
    </tbody>
</table>

@code {
    [Parameter]
    public IEnumerable<TItem> Items { get; set; } = [];

    [Parameter]
    public required Func<TItem, string> GetName { get; set; }

    [Parameter]
    public required Func<TItem, string> GetValue { get; set; }
}

Again, we define a generic type argument using the @typeparam directive at the top of the component.

In the code section, we use that type to implement three parameter properties. The Items property of type IEnumerable<TItem> contains a list of the provided items.

This list is looped through in the template section of the code, and for each item, the GetName and GetValue functions provided in the second and third component parameter are called.

Now, let’s see how we can use that component in our applications and why this implementation is as powerful as I advertised it.

@page "/"

<DataTable Items="persons"
           GetName="p => p.GetName()"
           GetValue="p => p.Age.ToString()" />

@code {
    private Person[] persons = [
        new Person { Name = "Peter Parker", Age = 22 }, 
        new Person { Name = "Mary Jane", Age = 20 }
    ];

    public class Person : INamedObject
    {
        public required string Name { get; set; }
        public required int Age { get; set; }

        public string GetName()
        {
            return Name;
        }
    }
}

Here, we have the same Person class we already used in the first chapter of this article. We create a list of Person objects and provide that list to the Items parameter of the DataTable component.

The magic happens in the definition of the GetName and GetValue parameter functions.

We use a lambda expression to define the behavior of the GetName and GetValue parameters.

For the Person class, we use its GetName method to render the person’s name, and for the value column, we use the Age property and call its ToString method.

By using a generic type argument, we can implement the behavior of the DataTable component outside the component definition.

Let’s look at a second example using a completely unrelated object:

@page "/"

<DataTable Items="animals"
           GetName="p => p.Name"
           GetValue="p => p.Type" />

@code {
    private Animal[] animals = [
        new Animal { Name = "Tom", Type = "Cat" },
        new Animal { Name = "Cherry", Type = "Mouse" }
    ];

    public class Animal
    {
        public required string Name { get; set; }
        public required string Type { get; set; }
    }
}

Here, we implement an Animal class with two properties Name and Type.

We want the animal’s name (what the owner calls the pet) and its type (kind of animal).

We can reuse the same DataTable component and provide a list of animals to the Items property. Again, type inference works perfectly; we do not need to explicitly provide the Animal type.

And again, we implement the behavior from outside the DataTable component when we use it, rather than when we define it. We use the Name property for the name column value and the Type property for the value column.

This example shows how to implement flexible, generic Razor components that let you share code across multiple uses of the same component and let each instance provide the behavior.

A Blazor web application with two data tables rendered using the same DataTable component. Both tables look and feel the same with a Name column and a Value column.

We can see that the look and feel of the first and the second list are exactly the same while we know that we provided two completely unrelated data types.

The Advantages of Generic Razor Components

We learned how to use the @typeparam directive to implement a generic type argument for Razor components.

We also implemented two examples that show how to build generic Razor components for your Blazor web applications.

Now, let’s look at the advantages of using generic type arguments in Razor components more broadly:

  1. Generic type arguments make components more reusable and keep them type-safe. Instead of using object as the base type of a parameter or using System.Reflection, the compiler provides a type-safe environment.
  2. Using the Func<TItem, ...> construct, we can inject/provide behavior from outside the component. It is possible to use different behavior in each component instance depending on the data provided.
    The component in our second example does not need to know whether it renders a list of animals, persons, or buildings. But it is responsible for providing a consistent and user-friendly experience.
  3. Thanks to type inference, we do not need to explicitly provide the generic type when using the component. Blazor can infer the type for us. This helps us keep the code concise and expressive.

In short: Generic type support lets us implement generic type arguments in Razor components, allowing us to reuse a type-safe component that provides a consistent look and feel and provides the behavior for each instance.

Conclusion

Generic Razor components are a powerful tool for building reusable and type-safe Blazor applications. By using the @typeparam directive, we can create components that work with different data types.

Generic components can separate a component’s presentation (rendering) from its data and behavior.

In the DataTable example component, we demonstrated how to use the same Razor component with two completely unrelated data classes.

Compared to implementing a Razor component for each data type and somehow finding a solution to share the template code, generic type arguments provide an elegant and concise solution.

If you want to learn more about Blazor development, watch my free Blazor Crash Course on YouTube. And stay tuned to the Telerik blog for more Blazor Basics.


About the Author

Claudio Bernasconi

Claudio Bernasconi is a passionate software engineer and content creator writing articles and running a .NET developer YouTube channel. He has more than 10 years of experience as a .NET developer and loves sharing his knowledge about Blazor and other .NET topics with the community.

Related Posts

Comments

Comments are disabled in preview mode.