C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Foreach: This loop acts upon the base.Controls collection. You are accessing each TextBox and Button (among others) in this loop.
ForeachHowever: The TextBox and Button instances are being accessed through a reference to their base class.
Casts: You can use the "is" and "as" casts to determine the derived type of the Control reference.
IsAsAlso: You can even mutate the properties of the Control instances by assigning their properties.
C# program that uses Control references
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Loop through each Control in ControlCollection.
foreach (Control control in base.Controls)
{
if (control is TextBox)
{
control.Text = "box";
}
else if (control is Button)
{
control.Text = "push";
}
}
}
}
}