Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Covariance

I have this simple code :

public interface IReader<out T>
{
    IEnumerable<T> GetData();
}

This interface should be covariant on T, and i'm using it this way :

private static Func<bool> MakeSynchroFunc<T>(IReader<T> reader) where T : IComposite
{
    return () => Synchronize(reader);
}

Note the constraint for T to implement IComposite. The synchronization method takes an IReader<IComposite> in input :

private static bool Synchronize(IReader<IComposite> reader)
{
    // ......
}

The compiler tells me it cannot convert from IReader<T> to IReader<IComposite> despite the constraint on T and the covariance of IReader.

Is there something i'm doing wrong here ? The compiler should be able to verify the constraint and the covariance should let me use my IReader<T> as an IReader<Icomposite>, isn't it ?

Thanks.

like image 639
dou bret Avatar asked Jun 20 '12 12:06

dou bret


1 Answers

You should be able to resolve your issue by adding a class constraint to T. Covariance does not work when structs are involved (IEnumerable<int> would not be convertible to IEnumerable<object>). Since you have not constrained T to be a class, you could pass in an IReader<some struct that implements IComposite>, which would not be convertible.

like image 52
Gideon Engelberth Avatar answered Sep 21 '22 15:09

Gideon Engelberth