views:

108

answers:

2

If I enter the code below, I get an error. Basically, the foreach will break when it comes across a Control that isn't a label.

foreach (Label currControl in this.Controls()) {

...
}

I have to do something like this.

foreach (Control currControl in this.Controls()) {
    if(typeof(Label).Equals(currControl.GetType())){

    ...
    }

}

can anyone think of a better way of doing it without me needing to check the type? Can I somehow get foreach to skip the objects that aren't Labels?

+9  A: 

If you're on .NET 3.5 or newer, you can do something like this

foreach(var label in this.Controls().OfType<Label>()) {
}

OfType<T> will ignore types that cannot be cast to T. See http://msdn.microsoft.com/en-us/library/bb360913.aspx

Brian Rasmussen
cool I just figured it out!any idea how you would do it without 3.5?
RoboShop
Cute syntax: This has me wondering if I can do this in Java 6...
Yar
+5  A: 

Brian has given the most appropriate answer in terms of OfType. However, I wanted to point out that there's a better way of checking for types in cases where you do need to do it. Instead of your current code:

if(typeof(Label).Equals(currControl.GetType())){

...
}

You can use:

if (currControl is Label)
{
    Label label = (Label) currControl;
    // ...
}

or:

Label label = currControl as Label;
if (label != null)
{
    // ...
}

Note that both of these alternatives will also include subclasses of Label, which your original code doesn't.

Jon Skeet
thanks will keep that in mind
RoboShop