I can restrict generics to a specify type using the "Where" clause such as:
public void foo<TTypeA>() where TTypeA : class, A
How do I do this if my function has two generic types?
public void foo<TTypeA, TTypeB>() where TTypeA : class, A && TTypeB : class, B
The above doesn't work. What's the correct syntax to add the rule "TTypeB : class, B"
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Reference type constraint This type of constraint specifies that the type argument should be a reference type. If we try to substitute a non-reference type for the type argument then we will get a compile-time error.
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.
public void foo<TTypeA, TTypeB>() where TTypeA : class, A where TTypeB : class, B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With