3

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);
}
trousyt
  • 360
  • 2
  • 12

1 Answers1

2

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.

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • I suppose I should just delegate this responsibility to the concrete class then and have it implement `IOneWayMapper` and `IOneWayMapper`. Thanks for the help. For anyone else, the link to that spec is http://msdn.microsoft.com/en-us/library/aa664592(v=vs.71).aspx – trousyt Oct 28 '14 at 21:54
  • @TroyP. Sounds like a reasonable solution :) – dcastro Oct 28 '14 at 21:55