10

Possible Duplicate:
Generic constraints, where T : struct and where T : class

Is there a particular reason that you cannot overload generic methods using mutually exclusive Type constraints in C#? For instance, take these methods:

T DoSomething<T>(T arg) where T : class
{ /* Do something */ }

T DoSomething<T>(T arg) where T : struct
{ /* Do something */ }

and try to invoke them with

DoSomething("1");
DoSomething(1);

The way I see it, the DoSomething() methods are mutually exclusive as far as the parameters that they will take - the first one takes a reference type, the second takes a value type. The compiler should be able to tell that the DoSomething call with a string argument goes to the first method and the DoSomething call with an int argument goes to the second method.

Am I missing something conceptually with generics here? Or is this just a feature that wasn't implemented in C#?

Community
  • 1
  • 1
eouw0o83hf
  • 9,438
  • 5
  • 53
  • 75
  • 1
    This duplicate text could be improved by adding a link to the duplicate answer. It's really frustrating if you can't find a solution and searching doesn't return any results, or way, way too many results. – John Paquin Feb 16 '17 at 05:58

1 Answers1

10

Generic constraints are not part of the method signature

See this answer Generic contraints on method overloads

Jon Skeet blog post on the topic

Community
  • 1
  • 1
asawyer
  • 17,642
  • 8
  • 59
  • 87