Multiple Generic Constraints .Net

Sukhpinder Singh | C# .Net
The Startup
Published in
2 min readAug 5, 2020

--

In this article, we will learn how to apply constraints with generics.

Generic Constraints In Action

Console GIF of generics constraints

Getting Started

In above link, we have learned about generics. Consider below example of simple generic type in which compiler does not know about placeholder type whether its a class or a interface etc.

To overcome that, we apply constraints to generics using “where” keyword. Constraints will result in compile time error if you instantiate with placeholder that is not defined in constraints.

For example, here we created a generic with two placeholders named “T1” and “T2” with constraints that T1 can only accept classes of “ModelExample3” and T2 with “ModelExample2”.

--

--

Sukhpinder Singh | C# .Net
The Startup

.Net Developer - I write about C# | .Net | ASP.Net | dotnet | .Net Aspire | MSSQL | Kubernetes | Angular | AWS Linktree: https://linktr.ee/sukhpindersingh