General method with specified types

Can I do something like this:

public void Foo<T>(int param) where T: MYCLASS1, MYCLASS2 

To indicate that T will only be an instance of MYCLASS1 or MYCLASS2?

Thanks..

+4
source share
4 answers

No, when you specify constraints of a general type, a generic argument of a type must satisfy all 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 # does not support multiple inheritance. General type constraints can be a combination of:

  • base class (only one allowed)
  • one or more interfaces
  • new() constraint (i.e. the type must have a constructor without parameters)
  • either struct or class (but not both, since the type cannot be a value type or a reference type)
+6
source

You cannot do this.

When adding restrictions to a generic type, you can specify only one class, and the others should be interfaces.

This is a valid limitation -

 public void Foo<T>(int param) where T: MyClass1, IInterface1, IInterface2 

But not this

 public void Foo<T>(int param) where T: MyClass1, MyClass2 

This is logical because when you declare a variable of type Foo, for example Foo<MyType> , your MyType can be derived from MyClass1 , IInterface1 and MyInterface2 , but it cannot be obtained from both MyClass1 and MyClass2 .

+1
source

No, general restrictions always coincide. You will need to perform 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"); // ... } 
+1
source

As Thomas points out, you cannot do this. However, you can do this:

 public void Foo<T>(int param) where T: IMyInterface 

While you know that both MYCLASS1 and MYCLASS2 implement IMyInterface

0
source

Source: https://habr.com/ru/post/1344298/


All Articles