Search code examples
genericsinheritanceparametersblazor

How to initialize a Blazor Component as Page with Generics


I habe a base Blazor component, using two generic classes like this

(base.razor)
@typeparam T where T : class
@typeparam P where P : class
...

(base.razor.cs)
public abstract partial class BaseClass<T, P> : ComponentBase where T : class where P : class
{
     [Parameter] public P? CurrentParent { get; set; }
...

I can easily load a derived class with a wrapper component like this:

@page "/mypage"

<Derived T="Class1" P="Class2" />
...

with this derived component:

@inherits BaseClass<T,P>
@{
    base.BuildRenderTree(__builder);
}
@code {
    @typeparam T where T : Class1
    @typeparam P where P : Class2

But when I try to call this derived component directly, with a @page it fails

@page "/direct"
@inherits BaseClass<T,P>
@{
    base.BuildRenderTree(__builder);
}
@code {
    @typeparam T where T : Class1
    @typeparam P where P : Class2

Trying to call the page in this way I get the following exception:

System.ArgumentException: Cannot create an instance of ...Pages.Derived`2[T,P] because Type.ContainsGenericParameters is true

I expect this is because the Parameter P is not given, can someone point me in the right direction of how to handle this without specifying the parameter or how to specify it?


Solution

  • When the page is called from somewhere else, the P and T types can't be left open.

    This ought to work:

    @page "/direct"
    @inherits BaseClass<Class1,Class2>
    @{
        base.BuildRenderTree(__builder);
    }
    @code {
     //   @typeparam T where T : Class1
     //   @typeparam P where P : Class2