0

I have a method that accepts a generic TViewModel class like so:

Page GetPage<TViewModel>() where TViewModel : class, IViewModelBase;

In my class I get the type of the item that the user selected (from a navigation list) like so:

var viewModel = item.TargetType;

This type will always be a view model that inherits from IViewModelBase

When I call this next line I need to be able to pass in the viewModel type. Im trying to do

var page = Navigator.GetPage<viewModel>();

But I get the following error:

viewModel is a variable but is being used like a type.

Is there anyway I can pass the viewModel type to the GetPage Method?

If not the only way I can see to do this is to have a switch statement that checks the viewModel type name and hard code the correct TViewModel into the GetPage call.

For example something like this:

switch (viewModel.Name)
{
    case "TaskViewModel":
            page = Navigator.GetPage<TaskViewModel>();
       break;
    case "TaskEditViewModel":
            page = Navigator.GetPage<TaskEditViewModel>();
       break;
}

I tried the solution that this was marked as a duplicate for and that answer does not apply to mine. I get the error

Object does not match target type

The attempted code looks like this:

MethodInfo method = typeof(Navigator).GetMethod("GetPage");
MethodInfo generic = method.MakeGenericMethod(viewModel);
generic.Invoke(this, null);
Bad Dub
  • 1,503
  • 2
  • 22
  • 52
  • 2
    In that case you probably want to pass a `Type` argument instead of using generics. Specifically generics expect the name of a type, not a variable of the `Type` class type. – juharr May 18 '18 at 13:14

1 Answers1

0

As I know generic methods or class generates at compile time. In method GetPage() as generic you can parameter pass any class whoes implements IViewModelBase. You can only pass viewModel like parameter you can do next:

Page GetPage<TViewModel>(TViewModel viewModel) where TViewModel : class, IViewModelBase;

and then you can use it like this:

GetPage<ImplementerIViewModelBase>(viewModel);

Where viewModel has type ImplementerIViewModelBase.

If you need know type of viewModel you can use typeof() or GetType() methods that return a Type instance. See example:

var type = viewModel.GetType();
/* some action */
if(type is ImplemeterIViewModelBase)
{
    /* some action */
}

You also can define generic method and implement him for each type:

//define
Page GetPage<TViewModel>(TViewModel viewModel) where TViewModel : class, 
IViewModelBase;

//Implement

Page GetPage<ImpolementerIViewModelBase1>(ImplementerIViewModelBase1 
viewModel)
{
    /* some implementation */
}

Page GetPage<ImpolementerIViewModelBase2>(ImplementerIViewModelBase2 
viewModel)
{
    /* some implementation */
}

etc

Ansver
  • 94
  • 9