An Interesting Use of a C# Foreach Loop

Posted on Tuesday, November 4, 2008

I've seen many different ways of clearing the contents of controls in a Windows Form object, some of which can be quite elaborate. While it can be fun to come up with these convoluted schemes, there is an easier way. Here's what I do...

I implement a foreach loop, and iterate over the form's collection of Controls, comparing each control to the TextBox control type, using the is keyword. This keyword, is, performs a type comparison. If the Control is the type I am comparing it to, then I perform a function call, in this case a call to the Control's ResetText() method.

The beauty of this chunk of code is that it scales with the form itself. If the form has 3 controls or 300, the same code can be applied without modification.

Pretty sweet, huh? Here's the code (written for C#):

foreach(Control ctrl in this.Controls)
    if( ctrl is TextBox )