Is there a way to declare a generic function that the generic type is of type1 or type2?
example:
public void Foo(T number)
{
}
I also had this problem and I think I found a better solution (assuming an overloaded version of your method is insufficient):
Mixing Type1
and Type2
without any parallels does not make any sense as has been written already. So there has to be any method or property accessed for both object types. To make sure for the compiler that these methods or properties are available for your object, group Type1
and Type2
by creating an interface MyInterface
and implementing it by Type1
and Type2
:
interface MyInterface {
void MyCommonMethod();
bool MyCommonProperty { get; }
}
class Type1 : MyInterface {
void MyCommonMethod() {
// TODO: Implement it for Type1
}
bool MyCommonProperty {
get {
// TODO: Implement it for Type1
}
}
}
class Type2 : MyInterface {
void MyCommonMethod() {
// TODO: Implement it for Type2
}
bool MyCommonProperty {
get {
// TODO: Implement it for Type2
}
}
}
Now, to rewrite your Foo
method to accept both Type1
and Type2
, constraint T
to be an MyInterface
object:
public void Foo(T number) where T : MyInterface
{
throw new NotImplementedException();
}
I mope this might be helpful. :)