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?
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
isand then casting again with the cast operator (parenthesis) is frowned upon.