Are generic type constraints possible in blazor?

Viewed 5140

How can I restrict TModel to be classes only or to be implementing a specific interface?

@typeparam TModel

cannot get the syntax working.

3 Answers

From ASP.NET Core 6.0 onwards, you can use the following syntax to specify generic type constraints:

@typeparam TModel where TModel : IModel

The solution is to put the type constraint additionally in a partial code behind class. It works!

Indeed, the answer posted by Sven works, but there is one modification I needed to do - add <RazorLangVersion>3.0</RazorLangVersion> to my .csproj file. After that the project was compiled. So here are my complete files:

  1. Project.cs
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <RazorLangVersion>3.0</RazorLangVersion> <!-- Important -->
    <Nullable>enable</Nullable>
    <ServiceWorkerAssetsManifest>service-worker-assets.js</ServiceWorkerAssetsManifest>
  </PropertyGroup>
</Project>
  1. Razor component
@typeparam TViewModel
@inherits PageBase<TViewModel>

<h3>Some text</h3>
  1. Corebehind
public abstract partial class AuthenticatedPageBase<TViewModel>
    where TViewModel : ViewModelBase
{
}

EDIT: Well, after deleting the <RazorLangVersion> tag from the csproj file it still seems to work.

Related