For example. Lets say we have a stackpanel on a form. Its full of both Grids and Labels. I want to loop through all the Grids and do some operation on them but leave the Lables intact. At the moment I am doing it this way.
foreach(UIElement element in m_stacker.Children)
{
Grid block = element as Grid;
if(block != null)
{
//apply changes here
}
}
So i'm using the fact that "as" returns null if it cannot cast into the required type. Is this an ok thing to do or is there a better solution to this problem?
What about OfType()?
foreach( var grid in m_stacker.Children.OfType<Grid>() ) { ... }
This will loop only over the children of type Grid, so no need to cast or check the type at all.
Yes, it's the right way to do it (considering "applying changes" will need to use the cast result).
However, if you are not going to use the cast return value, you can simply use is
.
Using is
and then casting again with the cast operator (parenthesis) is frowned upon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With