views:

339

answers:

4

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?

+2  A: 

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.

Rex M
this looks good, however, "Where" does not seem to appear in System.Web.UI.ControlCollection
Russ Bradberry
@Russ Where is an extension method on IEnumerable, same as OfType. As long as you have the System.Linq namespace included, you will have access to both methods.
Rex M
ControlCollection does not implement IEnumerable
Russ Bradberry
@Russ actually it does (see http://msdn.microsoft.com/en-us/library/system.web.ui.controlcollection.aspx), IEnumerable is required to do any iterative operation like foreach()
Rex M
The Linq Extensions are on IEnumerable<T> not IEnumerable, IEnumerable<T> is not implemented by ControlCollection, or am I missing something?
Russ Bradberry
@Russ sorry, OfType extends IEnumerable, Where extends IEnumerable<T>. We can solve this by converting the ControlCollection to an IEnumerable<Control>. See my updated answer.
Rex M
A: 

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())
Darin Dimitrov
A: 

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

Thomas Levesque
A: 

Have you tried something like this?

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