473,765 Members | 2,086 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does foreach raise exception when no elements of specified typeexist?

When I do this:
foreach( Button btn in myForm.Controls )

An exception is raised when no buttons exist. I would simply expect
execution to continue after the foreach loop (just as would be the case
with a regular for loop when the second expression is false when the
loop begins).

Is there an explanation for this?
Nov 17 '05 #1
8 2109
Hi,
No, an exception is throw when the first control that is not a Button is
found. if instead of

foreach( Button btn in myForm.Controls )

you write

foreach( Control btn in myForm.Controls )

you do not get that error

use this:
foreach( Button btn in myForm.Controls )
if ( btn is TextBox )
{
}
and take a look into OOP concepts as inheritance.

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Brad Wood" <bradley_.wood_ @ndsu_.edu> wrote in message
news:OI******** ******@TK2MSFTN GP14.phx.gbl...
When I do this:
foreach( Button btn in myForm.Controls )

An exception is raised when no buttons exist. I would simply expect
execution to continue after the foreach loop (just as would be the case
with a regular for loop when the second expression is false when the loop
begins).

Is there an explanation for this?

Nov 17 '05 #2
Another way to code this:

foreach (Control ctl in myForm.Controls )
{
Button btn = ctl as Button;
if (btn != null)
{
...
}
}

Nov 17 '05 #3
Ignacio Machin ( .NET/ C# MVP ) wrote:
Hi,
No, an exception is throw when the first control that is not a Button is
found. if instead of

foreach( Button btn in myForm.Controls )

you write

foreach( Control btn in myForm.Controls )

you do not get that error

use this:
foreach( Button btn in myForm.Controls )
if ( btn is TextBox )
{
}
and take a look into OOP concepts as inheritance.

cheers,


What I didn't understand is the way that the foreach loop works. I
thought it would implicitly only act on objects in the collection that
matched the declared type.
I understand that I could declare my foreach variable as a base Control,
but then I have to query each control's type. I thought the foreach
loop would preclude the extra code necessary on my part.
Nov 17 '05 #4
If you write foreach (Button btn in this.Controls)
it is expanded to code which does an explicit cast of each enumerated
element, so
(just for illustrative purpose)
Button btn = (Button)enumera tor.Current;
and this rises exception when the Current Contol is not a Button
Hope this answers your question

"Brad Wood" <bradley_.wood_ @ndsu_.edu> wrote in message
news:OR******** ******@tk2msftn gp13.phx.gbl...
Ignacio Machin ( .NET/ C# MVP ) wrote:
Hi,
No, an exception is throw when the first control that is not a Button is
found. if instead of

foreach( Button btn in myForm.Controls )

you write

foreach( Control btn in myForm.Controls )

you do not get that error

use this:
foreach( Button btn in myForm.Controls )
if ( btn is TextBox )
{
}
and take a look into OOP concepts as inheritance.

cheers,


What I didn't understand is the way that the foreach loop works. I
thought it would implicitly only act on objects in the collection that
matched the declared type.
I understand that I could declare my foreach variable as a base Control,
but then I have to query each control's type. I thought the foreach
loop would preclude the extra code necessary on my part.

Nov 17 '05 #5
foreach always iterates through every item in a collection, regardless
of what type you declare the receiving variable to be. For each item in
the collection, it attempts to cast that item to the type of variable
that you've supplied. If the cast fails, the foreach fails.

This is even clearer if you remember, as Lebesgue pointed out, that the
foreach loop just calls GetEnumerator() on the collection you pass it,
and the next item for each loop is just the result of calling
MoveNext() on the collection and then looking at the Current property.
You can "write" a foreach yourself like this:

IEnumerator en = myForm.Controls .GetEnumerator( );
while (en.MoveNext())
{
Button btn = (Button)en.Curr ent;
...
}

In theory, this should generate exactly the same code as

foreach (Button btn in myForm.Controls )
{
...
}

and, as you can see, the fact that the Current item is being cast to a
Button is separated from the call that moves to the next item, and,
indeed, the loop will fail on the line

Button btn = (Button)en.Curr ent;

because for some controls en.Current will not be a Button.

Nov 17 '05 #6
foreach loops through every item in a collection, regardless of the
type of variable you use to receive the individual items. As Lebesgue
pointed out, foreach is implemented, under the covers using an
IEnumerator. You can write your own "foreach" loop as follows:

IEnumerator en = myForm.Controls .GetEnumerator( );
while (en.MoveNext())
{
Button btn = (Button)en.Curr ent;
...
}

this is exactly equivalent to

foreach (Button btn in myForm.Controls )
{
...
}

As you can see, the "moving to next control" call is completely
separate from the "get current item and cast to Button" call.

Nov 17 '05 #7
Hi,

What I didn't understand is the way that the foreach loop works. I
thought it would implicitly only act on objects in the collection that
matched the declared type.


I suggest you to read a book about C# , will help you understand the core of
the language and will save you a lot of problem down the line
Nov 17 '05 #8
I misunderstood how the foreach loop works. I thought it would make an
implicit type comparison on each object. That would save me from having
to check each base control object's type against my desired type in the
loop.
It's too bad I can't just write a foreach loop with my desired
descendant type and go from there...
Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8436
by: Ed Brandmark | last post by:
I have a tag of the form <SCRIPT LANGUAGE="JavaScript1.1" SRC="foo.js"..... and was wondering if this delays the loading of my page until that file foo.js downloads. It seems that if I place this in the HEAD of my document - the page will wait until it downloads. If I place it in the BODY of my document - supposedly the page
11
2164
by: Grant Edwards | last post by:
I've read over and over that Python leaves floating point issues up to the underlying platform. This seems to be largely true, but not always. My underlying platform (IA32 Linux) correctly handles 1.0/0.0 and 0.0/0.0 according to the IEEE 754 standard, but Python goes out of its way to do the wrong thing. 1/0 is defined by the standard as +Inf and 0/0 is NaN.
4
1639
by: noname | last post by:
I'm learning C# generics recenly. How do i do to write the similar Java function below in C#? void printCollection(Collection<? extends A> c) { for (Object e: c) { System.out.println(e); }} In printCollection, I have to limit the bound of the argument, when is a generic of Collection with some classes inherites from A. Does anyone know
0
5115
by: Richard Gregory | last post by:
Hi, I have the wsdl below, for an Axis web service, and when I select Add Web Refernce in Visual Studio the proxy is missing a class representing the returnedElementsType (see reference.cs below the wsdl). This complex type is a collection of another complex type(elementType), and the Reference.cs has an array of these rather than the single returnedElementsType. If If I want to be able to obtain these elements from the SOAP response I...
3
2161
by: Emily | last post by:
Hi, I have the following code and an unhandled exception. Code: UnitInventory inventory; foreach (object obj in list) //debugger points to list where exception occurs {
7
1168
by: Steven W. Orr | last post by:
In my class I have class Error(Exception): """Base class for exceptions in this module.""" pass class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed.
29
4253
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to null and remove them afterwards? Thanks, Jon
10
18078
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I wanted to go through each entry(?) of ArrayList and remove some particular entry. So I tried following but it throws exception at runtime: foreach (myEntry entry in myArrayList) { // do something... if (entry.fieldA == 0)
14
4357
by: Rafe | last post by:
Hi, I've encountered a problem which is making debugging less obvious than it should be. The @property decorator doesn't always raise exceptions. It seems like it is bound to the class but ignored when called. I can see the attribute using dir(self.__class__) on an instance, but when called, python enters __getattr__. If I correct the bug, the attribute calls work as expected and do not call __getattr__. I can't seem to make a simple...
0
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10153
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9946
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8830
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5272
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3530
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2800
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.