Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are generic type constraints possible in blazor?

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

@typeparam TModel

cannot get the syntax working.

like image 384
CleanCoder Avatar asked Mar 17 '20 00:03

CleanCoder


People also ask

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

What are generic type constraints?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)

How do you create a generic component in Blazor?

To create generic Blazor components, you can use the @typeparam directive. In the example below, I first use a component that doesn't have a code-behind file. Then I show what you need to do when you have a code-behind file. The main “trick” is to use a partial class.

What is generic type constraints in C#?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.


2 Answers

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

@typeparam TModel where TModel : IModel
like image 93
Craig Brown Avatar answered Oct 20 '22 02:10

Craig Brown


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

like image 34
CleanCoder Avatar answered Oct 20 '22 02:10

CleanCoder