J. Lennon
J. Lennon

Reputation: 3361

Covariant in .net 3.5

I'm learning more about this world. And in my tests, I found this strange:

    [TestMethod]
    public void VarianceTest()
    {
        List<string> listValues = new List<string>();
        string[] arrayValues = listValues.ToArray();
        var result = HelperCoVariant.GetTest<int>(listValues); // error to compile
        var result2 = HelperCoVariant.GetTest<int>(arrayValues); // sucess
    }

Any Method:

public static class HelperCoVariant
{
    public static IEnumerable<T> GetTest<T>(this IEnumerable<object> t)
    {
        foreach (var item in t)
        {
            yield return (T)item;
        }
    }
}

I understand that the. NET 4 that works perfectly because of

IEnumerable<out T>

But why on. NET 3.5, there is this behavior?

Upvotes: 2

Views: 154

Answers (1)

phoog
phoog

Reputation: 43046

The next-to-last line does not compile because IEnumerable<T> does not have the out keyword in .NET 2/3/3.5. Since it doesn't have the out keyword, it cannot be treated as covariant in T.

The last line compiles because there is array covariance in earlier versions of C#. See Covariance and Contravariance in C#, Part Two: Array Covariance by Eric Lippert.

Upvotes: 4

Related Questions