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"?
>Solution :
Just use Enumerable.Cast(hard cast) or Enumerable.OfType(also filters):
IEnumerable<TextBox> allTextBoxes = uielementCollection.OfType<TextBox>();
In general you can’t use a generic methods if you know the type at runtime, generics are a compile time feature. So all you can do is to cast them to the desired type or the common base type. Then you can process them somewhere else by try-casting them to a specifiy type:
foreach (Control c in uielementCollection)
{
switch (c)
{
case TextBox txt:
// handle TextBox
break;
case Label lbl:
// handle Label
break;
// ... and so on
}
}