I am working in VB.net and have a Class, Foo, that implements an interface, IBar. I have a List of Foo's, but I need to pass a list of IBar's into a function, but I keep getting casting errors, even when I use DirectCast. My code is
Class Foo
Implements IBar
End Class
Interface IBar
End Interface
Sub DoIt(ByVal l As List(Of IBar))
End Sub
Sub Main()
Dim FooList As New List(Of Foo)
DoIt(FooList)
End Sub
Sub Main2()
Dim FooList As New List(Of Foo)
DoIt(DirectCast(FooList, List(Of IBar)))
End Sub
Sub MainWorks()
Dim FooList As New List(Of Foo)
Dim IBarList As New List(Of IBar)
For Each f As Foo In FooList
IBarList.Add(f)
Next
DoIt(DirectCast(IBarList, List(Of IBar)))
DoIt(IBarList)
End Sub
In both Main and Main2 I get
Value of type 'System.Collections.Generic.List(Of FreezePod.Pod.Foo)' cannot be converted to 'System.Collections.Generic.List(Of FreezePod.Pod.IBar)'.
MainWorks works, but it would be really annoying and inefficient to have to do that everywhere I want to call this function.