C# Fun with Generics - Mutual Dependencies

Posted by Kenneth Cochran on Stack Overflow See other posts from Stack Overflow or by Kenneth Cochran
Published on 2010-03-19T21:05:43Z Indexed on 2010/03/19 21:21 UTC
Read the original article Hit count: 266

Filed under:
|

As an experiment I'm trying to write a generic MVP framework.

I started with:

public interface IPresenter<TView> where TView: IView<IPresenter<...
{
    TView View { get; set;}
}

public interface IView<TPresenter> where TPresenter:IPresenter<IView<...
{
    TPresenter Presenter { get; set; }
}

Obviously this can't work because the types of TView and TPresenter can't be resolved. You'd be writing Type<Type<... forever. So my next attempt looked like this:

public interface IView<T> where T:IPresenter
{
    ...
}

public interface IView:IView<IPresenter>
{

}

public interface IPresenter<TView> where TView: IView
{
    ...
}

public interface IPresenter: IPresenter<IView>
{
    ...
}

This actually compiles and you can even inherit from these interfaces like so:

public class MyView : IView, IView<MyPresenter>
{
    ...
}

public class MyPresenter : IPresenter, IPresenter<MyView>
{
    ...
}

The problem is in the class definition you have to define any members declared in the generic type twice. Not ideal but it still compiles. The problem's start creeping up when you actually try to access the members of a Presenter from a View or vice versa. You get an Ambiguous reference when you try to compile. Is there any way to avoid this double implementation of a member when you inherit from both interfaces? Is it even possible to resolve two mutually dependent generic types at compile time?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics