Can I do something like this:
public void Foo<T>(int param) where T: MYCLASS1, MYCLASS2
To specify that T will only be MYCLASS1 or MYCLASS2 instance?
Thank you..
No, when you specify generic type constraints, the generic type argument must satisfy all the constraints, not just one of them. The code you wrote means that T
must inherit both MYCLASS1
and MYCLASS2
, which is not possible since C# doesn't support multiple inheritance. The generic type constraints can be a combination of:
new()
constraint (i.e. the type must have a parameterless constructor)struct
or class
(but not both, since a type can't be a value type and a reference type)No, generic constraints are always ANDed together. You will have to do a runtime check:
public void Foo<T>(int param) {
if (typeof(T) != typeof(MyClass1) && typeof(T) != typeof(MyClass2))
throw new ArgumentException("T must be MyClass1 or MyClass2");
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With