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?
Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.
forEach() does not make a copy of the array before iterating.
How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.
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 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.
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