Search code examples
.netvb.netreflectiontypesoftype

.Net Use Reflection To Define OfType


I am using System.Reflection to load a type that I cannot otherwise load during design time. I need to pull all controls within a collection of this type, however, i the OfType command doesn't seem to like the reflection Syntax. here is "close to" what I got.

Dim ControlType As Type = System.Reflection.Assembly.GetAssembly( _
                          GetType(MyAssembly.MyControl)) _
                         .GetType("MyAssembly.MyUnexposedControl")

Dim Matches as List(Of Control) = MyBaseControl.Controls.OfType(Of ControlType)

So that code is bogus, it doesn't work, but you get the idea of what I am trying to do. So is there a way to use reflection and get all of the controls that are of that type?


Solution

  • OfType is a generic method, so you can give it a static type (e.g. OfType(Of String)), not a System.Type determined at runtime.

    You could do something like:

    Dim CustomControlType as Type = LoadCustomType()
    
    MyBaseControl.Controls.Cast(Of Control)().Where(Function(ctrl) ctrl.GetType().IsAssignableFrom(CustomControlType))
    

    Using Cast(Of Control) to convert the ControlCollection (IEnumerable) to an IEnumerable<Control>, which then gets all the lambda extensions.