General restriction ignores codimension

Say we have an interface like

public interface IEnumerable<out T>
{ /*...*/ }

which is a co-option in T.

Then we have another interface and a class that implements it:

public interface ISomeInterface {}
public class SomeClass : ISomeInterface
{}

Now coincidence allows us to do the following

IEnumerable<ISomeInterface> e = Enumerable.Empty<SomeClass>();

So, IEnumerable<SomeClass>you can assign a type to a variable (or method parameter) IEnumerable<ISomeInterface>.

But if we try this in the general method:

public void GenericMethod<T>(IEnumerable<T> p) where T : ISomeInterface
{
    IEnumerable<ISomeInterface> e = p;
    // or
    TestMethod(p);
}
public void TestMethod(IEnumerable<ISomeInterface> x) {}

we get a CS0266 compiler error telling us that it IEnumerable<T>could not be converted to IEnumerable<ISomeInterface>.

The restriction clearly indicates what is Tobtained from ISomeInterface, and since it IEnumerable<T>is covariant in T, this assignment should work (as shown above).

- , ? -, , , ?

+6
1

GenericMethod class:

public void GenericMethod<T>(IEnumerable<T> p) where T : class, ISomeInterface
{
    IEnumerable<ISomeInterface> e = p;
    // or
    TestMethod(p);
}

, , .

+5

All Articles