7

In a Blazor component, you can create a generic parameter for use in a method just as you can in a typical C# class. To do this, the syntax is:

@typeparam T

But I would like to know how to constrain it as you can in a C# class. Something like

// pseudocode
@typeparam T : ICloneable 

For instance, I had the need to create the following component that allows a developer to pass a "Model" of generic type:

.../GESD.Blazor/Shared/GesdTrForm.razor

@typeparam modelType

<EditForm Model="@Model" 
    OnValidSubmit="@OnValidSubmit"
    style="display:table-row"
>
    @ChildContent
</EditForm>

@code {

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public modelType Model { get; set; } // here is the use of the generic

    [Parameter]
    public EventCallback<EditContext> OnValidSubmit { get; set; }

    void demo () {
        var cloned = Model.Clone();
    }

}

But at .Clone() I get the following error:

'modelType' does not contain a definition for 'Clone' ...

pwilcox
  • 5,542
  • 1
  • 19
  • 31
  • I know this is a duplicate of [this](https://stackoverflow.com/questions/60714729/are-generic-type-constraints-possible-in-blazor) question. However, I believe that question didn't have very much detail, and any thoughts I had on editing it pretty much had me rewriting it completely. If I'm out of line, of course vote to mark mine as a duplicate of that one, but I think the other question has problems. – pwilcox Oct 27 '20 at 19:00

2 Answers2

17

For future searchers, I have just found that this feature is available in .NET 6.

Usage looks like:

@typeparam T where T : IMyInterface

If the generic type cannot be determined by the compiler then it can be specified explicitly:

<MyComponent T=MyType>
Steve
  • 1,266
  • 16
  • 37
1

'.../GESD.Blazor/Shared/GesdTrForm.razor' creates a partial class called 'GesdTrForm' under the namespace 'GESD.Blazor.Shared'. Because it's a partial class, you can create a .cs file, delare the class as partial, and put the constraint in there.

.../GESD.Blazor/Shared/GesdTrForm.cs

using System;

namespace GESD.Blazor.Shared {

    public partial class GesdTrForm<modelType> where modelType : ICloneable {}

}
pwilcox
  • 5,542
  • 1
  • 19
  • 31