1

We know that co-variance allows us to do things like this:

IEnumerable<object> objects;
IEnumerable<string> strings = new[] { "hello", "world" };
objects = strings;

This code compiles, and works, due to co-variance.

However, if I use a bound generic, I get an error, as in the example:

void Test<T>(T blah) where T : ISerializable
{
    IEnumerable<T> x = new[] { blah };
    IEnumerable<ISerializable> y;
    y = x;
}

Gives the following error

[CS0266] Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'System.Collections.Generic.IEnumerable<System.Runtime.Serialization.ISerializable>'. 
An explicit conversion exists (are you missing a cast?)

In my head, this should work. I suspected that this could be related to some incompatibility with value types, and this was true. If I change the signature to

void Test<T>(T blah) where T : class, ISerializable

the code compiles with no errors.

But why? And how is this related to the error message?

Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41

0 Answers0