given that I have ViewModels with strongly typed parameter and I use NavigationService that accept type of page as a parameter, when parameter of incorrect type is passed to the Navigate method. then I want the compiler to throw an error.
I've written following so far:
interface IPageViewModel<TParameter>
void Navigate<TViewModel, TParameter>(TParameter argument)
where TViewModel : IPageViewModel<TParameter>;
class PageWithStringParameter : IPageViewModel<string>
Why this does not work?
navigationService.Navigate<PageWithStringParameter>("some string");
If I pass PageWithStringParameter as a TViewModel argument, TParameter must be of type string, since it implemets IPageViewModel. Passing TParameter type argument is redundant.
Is there any way, how to avoid writing this:
navigationService.Navigate<PageWithStringParameter, string>("some string");
The compiler errors are quite confusing, especialy if I have also parameterless overload of NavigateMethod
Method Navigate has two generic two type arguments. You are providing only one. Type arguments cannot be specified partially. You either specify all of them, or none of them (all should be resolved implicitly in that case)
An interface approach you could consider is to have Navigate without parameters return an operations object like below:
public class Operations<TViewModel>
{
void To<TParameter>(TParameter argument);
}
Operations<TViewModel> Navigate<TViewModel>();
So you can invoke the operation as such:
navigationService.Navigate<PageWithStringParameter>().To("some string");
Unfortunately you loose the ability to restrict type with the "where" clause, but you can do it with code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With