Russ Bradberry
Russ Bradberry

Reputation: 10865

.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?

Upvotes: 2

Views: 2392

Answers (4)

Rex M
Rex M

Reputation: 144112

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.

Upvotes: 3

jvanderh
jvanderh

Reputation: 2955

Have you tried something like this?

Dim query = From i In MyBaseControl.Controls Where i.GetType is ControlType

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Try like this:

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

Dim Matches as List(Of Control) = MyBaseControl.Controls.Where(Function(control) ControlType.GetType().IsAssignableFrom(control.GetType())

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292355

why not replace OfType with a Where in which you test the type ?

Dim Matches as List(Of Control) = MyBaseControl.Controls.Where(Function(ctl) ctl.GetType() = ControlType)

EDIT: darin was faster... and actually his solution is better because it handles derived classes

Upvotes: 0

Related Questions