Search code examples
.nettype-systemsgeneric-constraints

.NET Generics Type Constraint Inequality


I'm trying to implement two generic interfaces. It makes sense that ITwoWayMapper<T,U> would implement both IOneWayMapper<T,U> and IOneWayMapper<U,T>. So if I try to do just that:

public interface IOneWayMapper<T, U>
{
    U Map(T source);
}

public interface ITwoWayMapper<T, U> :
    IOneWayMapper<T, U>,
    IOneWayMapper<U, T>
{
    TTwo Map(TOne source);
    TOne Map(TTwo source);
}

I get the error Interface ITwoWayMapper<T,U> cannot implement both IOneWayMapper<T,U> and IOneWayMapper<U,T> because they may unify for some type parameter substitutions. So I think, well okay it makes sense that this is ambiguous because it couldn't tell which interface is being satisfied.

So this leads to my question: Is it possible to use type constraints to say something like this?:

public interface ITwoWayMapper<T, U> :
    IOneWayMapper<T, U>,
    IOneWayMapper<U, T>
    where T: !U
{
    TTwo Map(TOne source);
    TOne Map(TTwo source);
}

Solution

  • Section 13.4.2 of the C# Specification

    If any possible constructed type created from C would, after type arguments are substituted into L, cause two interfaces in L to be identical, then the declaration of C is invalid. Constraint declarations are not considered when determining all possible constructed types.

    So the answer is: no. Even if there was a type constraint such as T : !U, it would be ignored and you'd still bump into the same collision.