[2005] Get item type from Generic.List(of T) class
Hi
Given a class implementation like e.g.
Code:
Public Class MyControlList
Inherits Generic.List(Of Control)
End Class
How would I go about finding out what <T> type the generic list is of?
e.g.
Code:
Public Function ItemType(Byval CollectionType As Type) As Type
' ?? what magic code goes here
End Function
Re: [2005] Get item type from Generic.List(of T) class
Use something like:
Code:
If TypeOf ThingBeingChecked Is System.Windows.Forms.Label Then
'Do something
End If
Read up on the TypeOf operator.
Re: [2005] Get item type from Generic.List(of T) class
You can use the GetType function.
for example
Code:
Dim l As New List(Of Control)
l.Add(New TextBox)
l.Add(New ComboBox)
For Each lItem As Control In l
MsgBox(lItem.GetType.ToString)
Next
Re: [2005] Get item type from Generic.List(of T) class
Firstly, I recommend inheriting System.Collections.ObjectModel.Collection(Of T) when creating a typed collection.
Secondly, your MyControlList is NOT a generic class. It's just a class. If you wanted your class to be generic too then it would have to look like this:
vb.net Code:
Public Class ControlCollection(Of T As Control)
Inherits System.Collections.ObjectModel.Collection(Of T)
End Class
Now your class is generic too because it has a generic type parameter. That generic type is limited to be Control or some type derived from Control, so you can do this in code:
vb.net Code:
Dim buttons As New ControlCollection(Of Button)
Dim textBoxes As New ControlCollection(Of TextBox)
etc. but this would fail to compile:
vb.net Code:
Dim strings As New ControlCollection(Of String)
because the generic type you specified cannot be cast as type Control.
Now, to your original question. You've specifically stated in your class declaration that your class inherits List(Of Control), so there's no generic type to determine. If you are trying to determine the generic parameter types of a generic class you can do the likes of this:
vb.net Code:
Dim list1 As New List(Of String)
Dim list2 As New List(Of Form)
Dim list3 As New List(Of DataTable)
For Each t As Type In list1.GetType().GetGenericArguments()
MessageBox.Show(t.ToString(), "list1")
Next t
For Each t As Type In list2.GetType().GetGenericArguments()
MessageBox.Show(t.ToString(), "list2")
Next t
For Each t As Type In list3.GetType().GetGenericArguments()
MessageBox.Show(t.ToString(), "list3")
Next t