Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading based on generic constraints?

Tags:

c#

generics

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?

like image 480
Boris B. Avatar asked Sep 21 '12 11:09

Boris B.


People also ask

How can generic method 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 ...

What are generic constraints?

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.

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. The code below constrains a class to an interface.

Can a generic class have multiple constraints?

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.


2 Answers

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:

  • My blog post on the topic
  • Eric Lippert's blog post on the topic
like image 60
Jon Skeet Avatar answered Sep 20 '22 20:09

Jon Skeet


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?

like image 38
Oded Avatar answered Sep 20 '22 20:09

Oded