Search code examples
c#multithreadingasync-awaitcovarianceiasyncoperation

IAsyncOperation<IRandomAccessStream> not casting


I have this class CustomFileStream, below is its signature

public class CustomFileStream : IRandomAccessStream {}

But when I use it like this,

IAsyncOperation<IRandomAccessStream> IStorageFile.OpenAsync(FileAccessMode accessMode)
{
    return Task.Factory.StartNew(() => new CustomFileStream()).AsAsyncOperation();
}

I get a compilation error,

Cannot implicitly convert type 'Windows.Foundation.IAsyncOperation<CustomFileStream>' 
to 
'Windows.Foundation.IAsyncOperation<Windows.Storage.Streams.IRandomAccessStream>'

Can someone please see if I am doing something wrong here.

THanks.


Solution

  • This isn't possible due to the fact that IAsyncOperation<T> isn't covariant:

    Covariance enables you to use a more derived type than that specified by the generic parameter. This allows for implicit conversion of classes that implement variant interfaces and implicit conversion of delegate types.

    A covaraint interface is declared with the out modifier added to it in the generic type declaration, so as IEnumerable<out T>.

    To get around your problem, you can explicitly cast the returned instance back to an IRandomAccessStream:

    return Task.Factory.StartNew(() => (IRandomAccessStream)new CustomFileStream()).AsAsyncOperation();
    

    As a side note - using Task.Factory.StartNew to imitate asynchoronous behavior is bad practice. You shouldn't expose async wrappers over sync method calls