Search code examples
c#generics

Method overloading based on generic constraints?


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?


Solution

  • 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: