Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!