Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "as" and expecting a null return

Tags:

c#

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?

like image 841
DrLazer Avatar asked May 20 '10 11:05

DrLazer


2 Answers

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.

like image 90
tanascius Avatar answered Sep 28 '22 07:09

tanascius


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.

like image 28
mmx Avatar answered Sep 28 '22 08:09

mmx