Generics: How to derive from one of two classes?

Posted by Yaron Naveh on Stack Overflow See other posts from Stack Overflow or by Yaron Naveh
Published on 2010-03-18T20:49:50Z Indexed on 2010/03/18 21:11 UTC
Read the original article Hit count: 312

Filed under:
|

I have the following c# classes:

class A : Object
{
   foo() {}
}

class B : Object
{
   foo() {}
}

I want to write a generic method that applies to both:

void bar<T>(T t)
{
  t.foo();
}

this does not compile complaining the foo() is not a member of T. I can add a constraint for T to derive from one of the classes:

void bar<T>(T t) where T : A

but how can I have it for both?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics