Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inability to overload generic methods with type constraints [duplicate]

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#?

like image 545
eouw0o83hf Avatar asked Jan 25 '12 22:01

eouw0o83hf


People also ask

Can generic methods be overloaded?

A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.

What is generic type constraint?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.


1 Answers

Generic constraints are not part of the method signature

See this answer Generic contraints on method overloads

Jon Skeet blog post on the topic

like image 161
asawyer Avatar answered Sep 20 '22 17:09

asawyer