Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define constraints on multiple generics parameters

Tags:

c#

generics

I am wondering why I cant get such simple thing like this on google. This code is not compilable. How can I do this?

public class TestStep<StartEvent, CompletedEvent>      where StartEvent : MyBase1, MyInterface1, new() &&     where CompletedEvent : MyBase2, MyInterface2, new() { } 

Please help.

like image 533
D J Avatar asked Nov 08 '12 09:11

D J


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.

What are the constraints in generics?

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.

Can generic classes be constrained?

Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.

How do I restrict a generic class in C#?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.


1 Answers

Try without the "&&"

public class TestStep<StartEvent, CompletedEvent>      where StartEvent : MyBase1, MyInterface1, new()     where CompletedEvent : MyBase2, MyInterface2, new() { } 
like image 91
Greg Oks Avatar answered Sep 29 '22 13:09

Greg Oks