Home > Software design >  Compiler error while returning Task.FromResult(MyInterface): cannot implicitly convert types
Compiler error while returning Task.FromResult(MyInterface): cannot implicitly convert types

Time:10-05

I have two functions each returning an ActualObject instance, that implements interface MyInterface:

public class ActualObject : MyInterface
{
     ...
}

Task<MyInterface> GetObjectAsync()
{
    ActualObject obj = GetObjectInternal();
    return Task.FromResult(obj);
}

async Task<MyInterface> GetObjectAsync()
{
    ActualObject obj = await GetObjectInternalAsync();
    return obj;
}

GetObjectInternal() and GetObjectInternalAsync() both return the exact same object, just with two different implementations.

First method will give a compiler error: cannot implicitly convert from ActualObjectto MyInterface, while second method compiles fine. Why is that?

CodePudding user response:

Task.FromResult(obj) uses type inference to infer that you meant Task.FromResult<ActualObject>(obj), and then fails to convert that task type to the interface-based task type. (Task<T> is invariant.)

To fix this, you just need to specify the generic type argument for the call to FromResult:

return Task.FromResult<MyInterface>(obj);

(Or you could declare obj as type MyInterface...)

  • Related