I have a following hierarchy (I don't write here constructors and similar items for brevity):
Interface IData
ReadOnly Property ID As Integer
ReadOnly Property Name As String
End Interface
Public Class Data1
Implements IData
ReadOnly Property CoolProperty1 As String
End Class
Public Class Data2
Implements IData
ReadOnly Property CoolProperty2 As String
End Class
Now, the code in WinForms app is:
Dim a As List(Of IData) = {New Data1(1, "Name1", "Cool1_1"),
New Data1(1, "Name2", "Cool1_2")}.ToList();
someDataGridView.DataSource = a
When I do it, I only have columns ID and Name. In order to see column CoolProperty1, I have to do explicit Cast:
Sub FillDGV(ByVal lst as List(Of IData)
someDataGridView.DataSource = a.Cast(Of Data1).ToList()
End Sub
And if I account for class Data2, the Sub above becomes:
Sub FillDGV(ByVal lst as List(Of IData)
If Not lst.Any Then Return
If TypeOf lst.First Is Data1 Then
someDataGridView.DataSource = lst.Cast(Of Data1).ToList()
ElseIf TypeOf lst.First Is Data2 Then
someDataGridView.DataSource = lst.Cast(Of Data2).ToList()
Else
someDataGridView.DataSource = lst
EndIf
End Sub
I do understand why compiler does it like this, but I wonder if there's any nice pattern which would allow me to avoid such casts.
UPDATE: The thing is that my FillDGV function always receives list, which contains items of the same type, it is either List(Of Data1) or List(Of Data2).
SOLUTION: It seems I have an idea. Generics would help here:
Sub FillDGV(Of T As IData)(ByVal lst as List(Of T))
someDataGridView.DataSource = lst
End Sub