Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda