Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method with specified types

Tags:

c#

generics

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..

like image 206
bAN Avatar asked Feb 24 '23 18:02

bAN


2 Answers

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:

  • a base class (only one allowed)
  • one or several interfaces
  • the new() constraint (i.e. the type must have a parameterless constructor)
  • either struct or class (but not both, since a type can't be a value type and a reference type)
like image 145
Thomas Levesque Avatar answered Mar 06 '23 23:03

Thomas Levesque


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");
    // ...
}
like image 21
thecoop Avatar answered Mar 06 '23 23:03

thecoop