I want to refactor some functions that create asynchronously ViewModels. They were looking as follow :
public async Task NavigateToCreateFormVM()
{
try
{
IsLoading = true;
CurrentVM = await Task.Run(() => new CreateFormVM());
<...>
IsLoading = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "App", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
So in order to refactor all the logic, I tried writing a delegate to keep the code easy t maintain.
public async Task NavigationDelegate(Func<Task<BaseVM>> delegate)
{
try
{
IsLoading = true;
CurrentVM = await delegate();
<...>
IsLoading = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "App", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
and for example change my functions to :
public async Task NavigateToCreateFormVM()
{
await NavigationDelegate(() => Task.Run(() => new CreateFormVM()));
}
public async Task NavigateToConsultFormVM()
{
await NavigationDelegate(() => ConsultFormVM.CreateAsync()); // type of ConsultFormVM
}
But I get two error messages indicating that they can’t convert CreateFormVM/ConsultFormVM to BaseVM (they both inerith from BaseVM). If i change NavigationDelegate(Func<Task<BaseVM>> delegate)
to NavigationDelegate(Func<Task<CreateFormVM>> delegate)
it works with no problems.
The errors messages are CS0029 and CS1662.
Cannot implicitly convert type ‘System.Threading.Tasks.Task<Project.CreateFormVM>’ to ‘System.Threading.Tasks.Task<Project.BaseVM>’
Cannot convert anonymous method block to delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
I don’t know if I’m missing something or if I did something wrong (or if it shouldn’t be done this way at all ?) so I’d be grateful if soemone knew how to resolve my problem.