0

Let's suppose I have a class ClassA and a class ClassB, which are both totally different from each other.

For example:

public class ClassA {}
public class ClassB {}

And now I define two methods:

public void Foo<X>(X x) where X : ClassA {}
public void Foo<Y>(Y y) where Y : ClassB {}

As you can see, both Foo methods have the same name, the same return type, and the same amount of arguments. However, each method has a different constraint. Foo<X> can only accept a generic parameter that extends from ClassA, and Foo<Y> can only accept a generic parameter that extends from ClassB.

Nevertheless, the following error is thrown by the compiler:

Type Testing.Program already defines a member called Foo with the same parameter types

As far as I understand, each method accepts different parameter types.

What am I missing?

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 7
    generic constraints are not considered a part of method signature, hence can't be used for *overloading*, Also see: [Constraints are not part of the signature](http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx) – Habib Jan 23 '15 at 19:13
  • That's... dissapointing to hear :( Why are they not taken into account? – Matias Cicero Jan 23 '15 at 19:13
  • You can always get around this with type-checking within the generic method itself. Or renaming the generic method in a way that differentiates the two methods based on the generic constraints (`FooA`) – ryanyuyu Jan 23 '15 at 19:17

0 Answers0