Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method with a generic interface

Tags:

c#

generics

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?

like image 632
devGirl Avatar asked Aug 08 '26 18:08

devGirl


1 Answers

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");

like image 136
Anthony Pegram Avatar answered Aug 11 '26 06:08

Anthony Pegram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!