C # type conversion error despite common limitations

Why, with the general restriction on a parameter of type T of class P "should inherit from A", is the first call made, but the second call ends with the type conversion error indicated in the comment:

abstract class A { }

static class S
{
    public static void DoFirst(A argument) { }
    public static void DoSecond(ICollection<A> argument) { }
}

static class P<T>
    where T : A, new()
{
    static void Do()
    {
        S.DoFirst(new T());             // this call is OK

        S.DoSecond(new List<T>());      // this call won't compile with:

        /* cannot convert from 'System.Collections.Generic.List<T>'
           to 'System.Collections.Generic.ICollection<A>' */
    }
}

Should a general restriction ensure that List<T> really ICollection<A>?

+3
source share
3 answers

This is an example of the lack of C # covariance for generic types (C # supports array covariance). C # 4 will add this feature to interface types, and will also update several BCL interface types to support it.

. # 4.0: :

# 4.0. - , . , :)

+7

; , List , ICollection - # , ICollection:

S.DoSecond((ICollection<A>) new List<T>());      // this call will be happy
0

DoSecond ICollection <A> . , T A, List <T> ICollection <A> . ICollection <A> DoSecond, DoSecond .

. # 4.0, / , # 3.0.

0

Source: https://habr.com/ru/post/1714091/


All Articles