'Cast elements in UIElementCollection to Type of respective element

In an wpf-Application I want to cast the child elements of a Panel to the respective elements Type. For example, a UIElementCollection has 3 children: TextBox Button Label

If I iterate the UIElementCollection I'll get an UIElement and have to cast every element to it's Type before I can work with it.

So I tried to use a generic method, that will cast the UIElement to it's real type:

public static T getCastTo<T>(UIElement ele)
{                       
     return (T) (object) ele;
              
}

Using it by invoking

TextBox tb = SomeGenerics.getCastTo<TextBox>(ele);

gives me a TextBox as expected.

What I now want to do is using it in a loop something like

foreach(UIElement ele in uielementCollection) {
    SomeGenerics.getCastTo<ele.GetType()>(ele);  // or
    SomeGenerics.getCastTo<typeof(ele)>(ele);
}

but the compiler tells me that I can't use a variable as a Type. Is there a way to use the generic method without specifying the Type "manually"?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source