Mounilk... you can think of foreach is as just a shorthand that the
compiler
understands and then "writes" code for you. so for your example:
foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}
you can think of the compiler rewriting your code to:
IEnumerator enumerator= myTabPage.Controls.GetEnumerator();
while (enumerator.MoveNext())
{
MessageBox.Show (((TextBox)enumerator.Current).Text);
}
There are two potential problems with this compiler "generated" code.
First is
the cast (TextBox)enumerator.Currrent. Unless every item in the
enumeration
is a TextBox, the cast will eventually fail since this is an "unsafe"
cast. This
will result in an InvalidCastException. The second problem is that an
item in
an enumeration may be null. You cannot safely invoke a method on a null
reference in C#. (Other languages let you send a message to a null
object by
the way.) This will result in a NullReferenceException. So you need to
do some
checking inside the foreach loop as Tom's code shows. I prefer to use is
because I think it is clearer coding.
An is expression evaluates to true if both of the following conditions
are met:
expression is not null.
expression can be cast to type. That is, a cast expression of the form
(type)(expression) will complete without throwing an exception.
So the code would look something like:
foreach (object o in myTabPage.Controls)
{
if (o is TextBox)
{
MessageBox.Show (((TextBox)o).Text);
}
// else do nothing and move on to next object
}
These pages may help:
http://www.geocities.com/Jeff_Louie/OOP/oop6.htm http://www.geocities.com/Jeff_Louie/OOP/oop7.htm
Regards,
Jeff
*** Sent via Developersdex
http://www.developersdex.com ***