3

I'm trying to create a generic method where the type is a generic interface.

private void ShowView<T>(string viewName) where T : IView<Screen>
{ 
    IRegion mainRegion = _regionManager.Regions[RegionNames.MainRegion];
    T view = (T)mainRegion.GetView(viewName);
    if (view == null)
    {
        view = _container.Resolve<T>();
        mainRegion.Add(view, viewName);
    }
    mainRegion.Activate(view);
    view.LoadData();
    view.ViewModel.IsActive = true;
}

Interface is IView<T> where T : Screen.

So I have ConcreteView : IView<ConcreteViewModel> and ConcreteViewModel : Screen where Screen is the base class. When I try to do ShowView<ConcreteView>("concrete"); I get an UnknownMethod error.

Is it because ConcreteView uses ConcreteViewModel instead of Screen for it's IView implementation? Is there a way to rewrite the method so that it works?

1 Answer 1

7

IView<ConcreteViewModel> is not an IView<Screen> without providing variance to the interface

interface IView<out T>
{
}

(The above can be done starting in C# 4.0)

Otherwise, you should be able to write your method signature like below

void ShowView<T, U>(string viewName) where T : IView<U> where U : Screen
{
     // code
}

And invoke it like ShowView<ConcreteView, ConcreteViewModel>("blah");

Sign up to request clarification or add additional context in comments.

2 Comments

This is, because every generic interface is treated as a different one. Since .NET4.0 covariance is possible and so you could use the out statement.
OK. I had tried it without specifying <T, U> and kept getting an error. Thanks...that's what I was missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.