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#?
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 ...
Multiple interface constraints can be specified. The constraining interface can also be generic.
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.)
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.
Generic constraints are not part of the method signature
See this answer Generic contraints on method overloads
Jon Skeet blog post on the topic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With