In this article, we will learn how to apply constraints with generics.
Generic Constraints In Action
What is Generics in C#
Generics allows you to define placeholder for fields,methods,parameters etc. It replaces the placeholder with some…
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”.
How to create generics with constraints of multiple classes?
Below example shows a generic with two placeholders named “T1” and “T2” with constraints that T1 can only accepts classes of type “ModelExample3” and T2 can accept classes that implements “IModelExample” interface.
How to add mutiple types using generics. Contribute to ssukhpinder/MultipleGenericConstraint development by creating an…
More C# Concepts
I stand with .Net Core Framework
There are two supported .NET implementations for developing server-side apps: .NET Framework and .NET Core. However…
Generic Indexer .Net Core
This article demonstrates how to create a generic indexer using C#.
Say YES to String Interpolation
Many developers still use the “+” symbol to combine strings, but Microsoft has launched new features to write much…