Reputation: 29829
I'm trying to write a method to return a list of all of a particular type of control:
So I have something like the following method:
Private Function GetAllChildControls(Of T)(ByVal grid As DataGridItemCollection)
As List(Of T)
Dim childControls As New List(Of T)
For Each item As DataGridItem In grid
For Each tableCell As TableCell In item.Cells
If tableCell.HasControls Then
For Each tableCellControl As Control In tableCell.Controls
If tableCellControl.GetType Is GetType(T) Then
childControls.Add(DirectCast(tableCellControl, T))
End If
Next
End If
Next
Next
Return childControls
End Function
But this fails on the following code:
childControls.Add(DirectCast(tableCellControl, T))
I get the message:
Cannot cast expression of type
System.Web.UI.Control
to typeT
.
How can I return a type specific list?
Upvotes: 0
Views: 134
Reputation: 29829
Generics can be anything, so the compiler has no way of knowing that you only intend to call this method on types that inherit from System.Web.UI.Control
. You could, in fact, call the function with Type Integer
, in which case the conversion will fail.
What you need to do is convince the compiler that you will only pass in certain types by using Generic Constraints. Then you can only allow applicable types to call into the method.
All you need to do is modify your signature like this:
Private Function GetAllChildControlsInDataGrid(Of T As Control)(
ByVal grid As DataGridItemCollection) As List(Of T)
Upvotes: 1