.NET Generics Type Constraint Inequality

I am trying to implement two common interfaces. It makes sense that both ITwoWayMapper<T,U>

will implement IOneWayMapper<T,U>

and IOneWayMapper<U,T>

. So if I try to do exactly this:

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 am getting an 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 it's good that it makes sense as it is ambiguous because it couldn't figure out which interface is being executed.

So this leads to my question: can type constraints be used 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);
}

      

+3


source to share


1 answer


Section 13.4.2 C # Specifications

If any possible constructed type created from C, after the type arguments have been replaced with L, causes the two interfaces in L to be identical, then the declaration of C is invalid. Constraint declarations are ignored in determining all possible built types.



So the answer is no. Even if there is a type constraint, for example T : !U

, it will be ignored and you will still face the same collision.

+2


source







All Articles