Can I somehow have overloaded methods which differ only by generic type constraints?
This does not compile:
void Foo<T>(T bar) where T : class
{
}
void Foo<T>(T bar) where T : struct
{
}
Since these are "open" methods, the actual method should be closed/constructed/fully-defined when it's referenced elsewhere in code with a concretely-typed T
, and then it would be clear which overload to call.
The obvious solution is not to overload them, but I'm wondering why this doesn't work in C#?
Additional question: If this is just a C# compiler constraint, does the IL allow such an overload?
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 ...
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
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. The code below constrains a class to an interface.
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
Can I somehow have overloaded methods which differ only by generic type constraints?
No. It's not part of the method signature in terms of overloading, just like the return type isn't.
There are horrible ways of "pseudo-overloading" in some cases, but I wouldn't recommend going down that path.
For more information, you might want to read:
This is not possible.
Generic constraints are not considered to be part of the method signature for purposes of overloading.
If you want to allow both value types and reference types, why constrain at all?
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