Have been reading up and checking other questions, but don’t understand / can’t seem to find my answer anywhere else.
Assume the following
Public Interface IAudit
Public Class FamilyAudit implements IAudit
Public Class MemberAudit implements IAudit
Public Class AuditPair(Of T As IAudit)
Dim myList as new List(of AuditPair(of IAudit))
Dim famAuditPair as new AuditPair(of FamilyAudit)
Dim memAuditPair as new AuditPair(of MemberAudit)
' This fails
myList.Add(famAuditPair)
myList.Add(memAuditPair)
I get compiler error that the auditPairs cannot be implicitly converted to AuditPair(of IAudit). This looks like co/contra variance.
The MSDN doc says that since 4.0 Lists should be supporting variance.
What am I missing?
The new
in/outvariance feature applies specifically to two scenarios:It does not apply directly to concrete types list
List<T>. And further, a “list” is intrinsically non-variant, since the “add” and “enumerate” would be mutually incompatible in either direction. However, a list acting as a sequence is covariant. Consider:Note that this only applies to .NET 4.0 and above; on earlier versions it will refuse to compile, saying:
That is because prior to 4.0, the interface is
IEnumerable<T>, rather than the necessaryIEnumerable<out T>.