Question

I have the following interface definition:

public interface IResEnume<out TModel> : IEnumerable<TModel> where TModel : IModel
{
}

where IModel is

public interface IModel
{
    int Id { get; }
}

This works fine when the target framework is .NET 4.

I'm trying to port a class library to Windows Phone 7.1.

When doing this I get the following error:

Invalid variance: The type parameter 'TModel' must be invariantly valid >on 'System.Collections.Generic.IEnumerable'. 'TModel' is covariant.

If I remove the 'out' that line compiles, but then I get an error someplace else.

Was it helpful?

Solution

This is because the T parameter on IEnumerable<T> is not covariant in Silverlight. Conveniently, MSDN says it is covariant, however in the community content, someone else points out the same thing:

Despite the documentation above, the generic type parameter T does not appear to be covariant in Silverlight.

We can verify this in the Object Browser. In .NET Framework 4:

.NET 4

Notice the type declaration includes the out.

And for Windows Phone 7:

Silverlight

There is no out in Windows Phone IEnumerable. You cannot declare TModel covariant because IEnumerable<T> does not guarantee that it is a covariant. There is no reason it couldn't be this case; Microsoft just needs to update it.

EDIT: After some digging, looks like this is a known issue on Microsoft Connect which is marked as "fixed". It's likely been fixed for Silverlight 5; which Windows Phone is not yet using.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top