490

Possible Duplicate:
Generic methods and multiple constraints

I need a generic function that has two type constraints, each inheriting from a different base class. I know how to do this with one type:

void foo<T>() where T : BaseClass

However, I don't know how to do this with two types:

void foo<TOne, TTwo>() where TOne : BaseOne // and TTwo : BaseTwo ???

How do you do this? (using .NET 2)

Community
  • 1
  • 1
Jon B
  • 51,025
  • 31
  • 133
  • 161

1 Answers1

860
void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#constraining-multiple-parameters

Joel Martinez
  • 46,929
  • 26
  • 130
  • 185
  • 11
    Search for "Constraining Multiple Parameters" if you don't want to read it all. – RichardOD Jun 08 '09 at 15:51
  • 3
    Is it possible to have a constrain that would do this: `void foo() where TOne : Class where TTwo : Class where TOne != TTwo` so basically we don't know what TOne and TTwo are except that they are reference types but cannot be the same – IronHide Jun 23 '16 at 09:20
  • 1
    @IronHide: I'd love to be proven wrong here ... but I'm 99% sure this isn't possible :) – Joel Martinez Jul 21 '16 at 19:55
  • And how to use ExtensionMethod with multiple generics – mincasoft Nov 22 '19 at 15:50