Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify multiple generic type constraints on a single method?

Tags:

c#

generics

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"

like image 233
Justin Avatar asked Jul 07 '10 18:07

Justin


People also ask

Can a generic class have multiple constraints?

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.

Which keyword is used to specifying constraints for generics type parameters?

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.

Which constraints should be used to create a generic class that should only work with reference types?

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.

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.


1 Answers

 public void foo<TTypeA, TTypeB>() where TTypeA : class, A                                     where TTypeB : class, B  
like image 174
James Curran Avatar answered Sep 21 '22 15:09

James Curran