OfType: Finding Objects of a Particular Type
Posted
Fri, Jul 3 2009 8:52
by
Deborah Kurata
I ran across the OfType feature a few months ago and find it to be very useful. OfType is one of the many extension methods on IEnumerable that was provided with .NET 3.5.
If you ever need to search through a list for a particular type of object, then this feature is for you. The most common scenario for this feature is in working with the user interface. Say you want to hook up a particular event handler to every Button on your form. Or you want to go through your form and clear every TextBox.
Previously, you would have to use a for or for/each loop and check the type of each object before you process it. Now, you can do this…
In VB:
For Each tb As TextBox In activeTab.Controls.OfType(Of TextBox)()
tb.Text = String.Empty
Next
In C#:
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
tb.Text = string.Empty;
}
Enjoy!