Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type argument in generic class

Tags:

c#

generics

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

like image 828
Liero Avatar asked Jul 09 '26 23:07

Liero


2 Answers

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)

like image 138
Sergey Berezovskiy Avatar answered Jul 11 '26 14:07

Sergey Berezovskiy


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.

like image 27
Michael Erickson Avatar answered Jul 11 '26 14:07

Michael Erickson



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!