Alex Rivera | Logout

C# Pass Generics At Runtime

Asked 2010-04-09T14:26:44.773
10

I have a method like the following:

public IEnumerable<T> GetControls<T>()
 : where T : ControlBase
{
 // removed.
}

I then created a class:

public class HandleBase<TOwner> : ControlBase
 : TOwner
{
 // Removed
}

I'd like to be able to call

GetControls<HandleBase<this.GetType()>>; 

where it would use the type of THIS class to pass to the HandleBase. This would in essentially get all HandleBase that have an owner of THIS type.

How can I achieve this?

EDIT:

I'm using .NET 2.0 so solutions greater than 2.0 will not work.

The idea is to have ControlBase have a collection of other ControlBase for "children". Then they can be queried based on their type with GetControls<T>(). This would allow me to, for example, get all HandleBase for a Shape. Then I can take all of these and set Visible=false or do something else with them. Thus I can manipulate children of a specific type for a collection.

HandleBase<TOwner> requires the TOwner since it has a reference to the "owning type". So you can only add anything that extends HandleBase to a Shape. Make sense?

Thanks for all the help!

Edit
Report

1 Answer

0

Since GetControls() returns an enumeration, you might find a way to filter the resulting enumeration with .OfType<T>, something like

List<T2> list = controlList.GetControls<T>().OfType<T2>().ToList();

You would need a generic constraint somehwere along the lines of

where T2 : T
answered 2010-04-09T14:50:36.440

Your Answer