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:

<!-- language: lang-vb -->
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:

<!-- language: lang-vb -->
childControls.Add(DirectCast(tableCellControl, T))

I get the message:

Cannot cast expression of type System.Web.UI.Control to type T.

How can I return a type specific list?

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:

<!-- language-all: lang-vb --> <pre><code>Private Function GetAllChildControlsInDataGrid(Of T <b>As Control</b>)( ByVal grid As DataGridItemCollection) As List(Of T) </code></pre>