Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
Using Task.FromResult to implicitly convert a Task<T> to a Task<X> where T : X?
Task<IDictionary<double, double>> GetTaskDict()
{
     return Task.FromResult(new Dictionary<double, double> () );
}

This code does not compile because we can not convert between Task<Dictionary<double, double>> to Task<IDictionary<double, double>>. Why does this not work, and is it possible to make this type of call work? This opposed to a method like this which compiles

IDictionary<double, double> GetTaskDict()
{
     return new Dictionary<double, double> ();
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

return Task.FromResult<IDictionary<double, double>>(new Dictionary<double, double>());

This is because Task<T> is not covariant, so a Task<Foo> is not interchangeable with a Task<IFoo> even if Foo : IFoo.

You may also wish to consider using ValueTask<T> if you're going to have lots of results which are available synchronously - it is significantly cheaper in that scenario. You can even use the implicit new() usage in that scenario:

ValueTask<IDictionary<double, double>> GetTaskDict()
{
    return new(new Dictionary<double, double>());
}

(here, new(...) is interpreted as new ValueTask<IDictionary<double, double>>(...) from the declared return-type of the method)

over 4 years ago · Santiago Trujillo Relatório

0

Suppose it were possible.

Then someone could do this:

Task<IDictionary<double, double>> myTaskDict = new Task<Dictionary<double, double>>();

Task.SetResult(myIDictionaryWhichIsNotActuallyADictionary);

In other words, as @MarcGravell has said, Task is not covariant, and for very good reason.


You can specify the type explicitly like this though:

Task<IDictionary<double, double>> GetTaskDict()
{
     return Task.FromResult<IDictionary<double, double>>(new Dictionary<double, double>());
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda